blob: f79a48e3bda5092dc0db82ac19c2eaa092a6c277 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattnerc8e66542002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
90
Chris Lattner99f48c62002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000093 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000095
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000099 }
100
Chris Lattner69193f92004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000109 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner0798af32005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000141 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000142
143 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000144 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145
Chris Lattner970c33a2003-06-19 17:00:31 +0000146 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000147 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000148 bool transformConstExprCastCall(CallSite CS);
149
Chris Lattner69193f92004-04-05 01:30:19 +0000150 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 // InsertNewInstBefore - insert an instruction New before instruction Old
152 // in the program. Add the new instruction to the worklist.
153 //
Chris Lattner623826c2004-09-28 21:48:02 +0000154 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000155 assert(New && New->getParent() == 0 &&
156 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000157 BasicBlock *BB = Old.getParent();
158 BB->getInstList().insert(&Old, New); // Insert inst
159 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000160 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000161 }
162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
164 /// This also adds the cast to the worklist. Finally, this returns the
165 /// cast.
166 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
167 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000168
Chris Lattnere79d2492006-04-06 19:19:17 +0000169 if (Constant *CV = dyn_cast<Constant>(V))
170 return ConstantExpr::getCast(CV, Ty);
171
Chris Lattner7e794272004-09-24 15:21:34 +0000172 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
173 WorkList.push_back(C);
174 return C;
175 }
176
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 // ReplaceInstUsesWith - This method is to be used when an instruction is
178 // found to be dead, replacable with another preexisting expression. Here
179 // we add all uses of I to the worklist, replace all uses of I with the new
180 // value, then return I, so that the inst combiner will know that I was
181 // modified.
182 //
183 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000184 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000185 if (&I != V) {
186 I.replaceAllUsesWith(V);
187 return &I;
188 } else {
189 // If we are replacing the instruction with itself, this must be in a
190 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000191 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000192 return &I;
193 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000194 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000195
Chris Lattner2590e512006-02-07 06:56:34 +0000196 // UpdateValueUsesWith - This method is to be used when an value is
197 // found to be replacable with another preexisting expression or was
198 // updated. Here we add all uses of I to the worklist, replace all uses of
199 // I with the new value (unless the instruction was just updated), then
200 // return true, so that the inst combiner will know that I was modified.
201 //
202 bool UpdateValueUsesWith(Value *Old, Value *New) {
203 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
204 if (Old != New)
205 Old->replaceAllUsesWith(New);
206 if (Instruction *I = dyn_cast<Instruction>(Old))
207 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000208 if (Instruction *I = dyn_cast<Instruction>(New))
209 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000210 return true;
211 }
212
Chris Lattner51ea1272004-02-28 05:22:00 +0000213 // EraseInstFromFunction - When dealing with an instruction that has side
214 // effects or produces a void value, we can't rely on DCE to delete the
215 // instruction. Instead, visit methods should return the value returned by
216 // this function.
217 Instruction *EraseInstFromFunction(Instruction &I) {
218 assert(I.use_empty() && "Cannot erase instruction that is used!");
219 AddUsesToWorkList(I);
220 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000221 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000222 return 0; // Don't do anything with FI
223 }
224
Chris Lattner3ac7c262003-08-13 20:16:26 +0000225 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000226 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
227 /// InsertBefore instruction. This is specialized a bit to avoid inserting
228 /// casts that are known to not do anything...
229 ///
230 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
231 Instruction *InsertBefore);
232
Chris Lattner7fb29e12003-03-11 00:12:48 +0000233 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000234 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000235 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000236
Chris Lattner0157e7f2006-02-11 09:31:47 +0000237 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
238 uint64_t &KnownZero, uint64_t &KnownOne,
239 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000240
241 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
242 // PHI node as operand #0, see if we can fold the instruction into the PHI
243 // (which is only possible if all operands to the PHI are constants).
244 Instruction *FoldOpIntoPhi(Instruction &I);
245
Chris Lattner7515cab2004-11-14 19:13:23 +0000246 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
247 // operator and they all are only used by the PHI, PHI together their
248 // inputs, and do the operation once, to the result of the PHI.
249 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
250
Chris Lattnerba1cb382003-09-19 17:17:26 +0000251 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
252 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000253
254 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
255 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000256 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
257 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000258 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000259 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000260
Chris Lattnerc8b70922002-07-26 21:12:46 +0000261 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000262}
263
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000264// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000265// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266static unsigned getComplexity(Value *V) {
267 if (isa<Instruction>(V)) {
268 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000269 return 3;
270 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000271 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000272 if (isa<Argument>(V)) return 3;
273 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000274}
Chris Lattner260ab202002-04-18 17:39:14 +0000275
Chris Lattner7fb29e12003-03-11 00:12:48 +0000276// isOnlyUse - Return true if this instruction will be deleted if we stop using
277// it.
278static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000279 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280}
281
Chris Lattnere79e8542004-02-23 06:38:22 +0000282// getPromotedType - Return the specified type promoted as it would be to pass
283// though a va_arg area...
284static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000285 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000286 case Type::SByteTyID:
287 case Type::ShortTyID: return Type::IntTy;
288 case Type::UByteTyID:
289 case Type::UShortTyID: return Type::UIntTy;
290 case Type::FloatTyID: return Type::DoubleTy;
291 default: return Ty;
292 }
293}
294
Chris Lattner567b81f2005-09-13 00:40:14 +0000295/// isCast - If the specified operand is a CastInst or a constant expr cast,
296/// return the operand value, otherwise return null.
297static Value *isCast(Value *V) {
298 if (CastInst *I = dyn_cast<CastInst>(V))
299 return I->getOperand(0);
300 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
301 if (CE->getOpcode() == Instruction::Cast)
302 return CE->getOperand(0);
303 return 0;
304}
305
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306// SimplifyCommutative - This performs a few simplifications for commutative
307// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000308//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000309// 1. Order operands such that they are listed from right (least complex) to
310// left (most complex). This puts constants before unary operators before
311// binary operators.
312//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000313// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
314// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000315//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000316bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000317 bool Changed = false;
318 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
319 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000320
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321 if (!I.isAssociative()) return Changed;
322 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000323 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
324 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
325 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000326 Constant *Folded = ConstantExpr::get(I.getOpcode(),
327 cast<Constant>(I.getOperand(1)),
328 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000329 I.setOperand(0, Op->getOperand(0));
330 I.setOperand(1, Folded);
331 return true;
332 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
333 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
334 isOnlyUse(Op) && isOnlyUse(Op1)) {
335 Constant *C1 = cast<Constant>(Op->getOperand(1));
336 Constant *C2 = cast<Constant>(Op1->getOperand(1));
337
338 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000339 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000340 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
341 Op1->getOperand(0),
342 Op1->getName(), &I);
343 WorkList.push_back(New);
344 I.setOperand(0, New);
345 I.setOperand(1, Folded);
346 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000347 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000348 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000349 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000350}
Chris Lattnerca081252001-12-14 16:52:21 +0000351
Chris Lattnerbb74e222003-03-10 23:06:50 +0000352// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
353// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000354//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000355static inline Value *dyn_castNegVal(Value *V) {
356 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000357 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000358
Chris Lattner9ad0d552004-12-14 20:08:06 +0000359 // Constants can be considered to be negated values if they can be folded.
360 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
361 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000362 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000363}
364
Chris Lattnerbb74e222003-03-10 23:06:50 +0000365static inline Value *dyn_castNotVal(Value *V) {
366 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000367 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000368
369 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000370 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000371 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000372 return 0;
373}
374
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375// dyn_castFoldableMul - If this value is a multiply that can be folded into
376// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000377// non-constant operand of the multiply, and set CST to point to the multiplier.
378// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000379//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000380static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000381 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000382 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000383 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000384 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000385 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000386 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000387 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000388 // The multiplier is really 1 << CST.
389 Constant *One = ConstantInt::get(V->getType(), 1);
390 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
391 return I->getOperand(0);
392 }
393 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000394 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000395}
Chris Lattner31ae8632002-08-14 17:51:49 +0000396
Chris Lattner0798af32005-01-13 20:14:25 +0000397/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
398/// expression, return it.
399static User *dyn_castGetElementPtr(Value *V) {
400 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
402 if (CE->getOpcode() == Instruction::GetElementPtr)
403 return cast<User>(V);
404 return false;
405}
406
Chris Lattner623826c2004-09-28 21:48:02 +0000407// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000408static ConstantInt *AddOne(ConstantInt *C) {
409 return cast<ConstantInt>(ConstantExpr::getAdd(C,
410 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000411}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000412static ConstantInt *SubOne(ConstantInt *C) {
413 return cast<ConstantInt>(ConstantExpr::getSub(C,
414 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000415}
416
Chris Lattner0157e7f2006-02-11 09:31:47 +0000417/// GetConstantInType - Return a ConstantInt with the specified type and value.
418///
Chris Lattneree0f2802006-02-12 02:07:56 +0000419static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000420 if (Ty->isUnsigned())
421 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000422 else if (Ty->getTypeID() == Type::BoolTyID)
423 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000424 int64_t SVal = Val;
425 SVal <<= 64-Ty->getPrimitiveSizeInBits();
426 SVal >>= 64-Ty->getPrimitiveSizeInBits();
427 return ConstantSInt::get(Ty, SVal);
428}
429
430
Chris Lattner4534dd592006-02-09 07:38:58 +0000431/// ComputeMaskedBits - Determine which of the bits specified in Mask are
432/// known to be either zero or one and return them in the KnownZero/KnownOne
433/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
434/// processing.
435static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
436 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000437 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
438 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000439 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000440 // optimized based on the contradictory assumption that it is non-zero.
441 // Because instcombine aggressively folds operations with undef args anyway,
442 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000443 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
444 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000445 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000446 KnownZero = ~KnownOne & Mask;
447 return;
448 }
449
450 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000451 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000452 return; // Limit search depth.
453
454 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000455 Instruction *I = dyn_cast<Instruction>(V);
456 if (!I) return;
457
458 switch (I->getOpcode()) {
459 case Instruction::And:
460 // If either the LHS or the RHS are Zero, the result is zero.
461 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
462 Mask &= ~KnownZero;
463 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
464 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
465 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
466
467 // Output known-1 bits are only known if set in both the LHS & RHS.
468 KnownOne &= KnownOne2;
469 // Output known-0 are known to be clear if zero in either the LHS | RHS.
470 KnownZero |= KnownZero2;
471 return;
472 case Instruction::Or:
473 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
474 Mask &= ~KnownOne;
475 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
476 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
477 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
478
479 // Output known-0 bits are only known if clear in both the LHS & RHS.
480 KnownZero &= KnownZero2;
481 // Output known-1 are known to be set if set in either the LHS | RHS.
482 KnownOne |= KnownOne2;
483 return;
484 case Instruction::Xor: {
485 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
486 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
487 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
488 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
489
490 // Output known-0 bits are known if clear or set in both the LHS & RHS.
491 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
492 // Output known-1 are known to be set if set in only one of the LHS, RHS.
493 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
494 KnownZero = KnownZeroOut;
495 return;
496 }
497 case Instruction::Select:
498 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
499 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
500 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
501 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
502
503 // Only known if known in both the LHS and RHS.
504 KnownOne &= KnownOne2;
505 KnownZero &= KnownZero2;
506 return;
507 case Instruction::Cast: {
508 const Type *SrcTy = I->getOperand(0)->getType();
509 if (!SrcTy->isIntegral()) return;
510
511 // If this is an integer truncate or noop, just look in the input.
512 if (SrcTy->getPrimitiveSizeInBits() >=
513 I->getType()->getPrimitiveSizeInBits()) {
514 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000515 return;
516 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000517
Chris Lattner0157e7f2006-02-11 09:31:47 +0000518 // Sign or Zero extension. Compute the bits in the result that are not
519 // present in the input.
520 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
521 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000522
Chris Lattner0157e7f2006-02-11 09:31:47 +0000523 // Handle zero extension.
524 if (!SrcTy->isSigned()) {
525 Mask &= SrcTy->getIntegralTypeMask();
526 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
527 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
528 // The top bits are known to be zero.
529 KnownZero |= NewBits;
530 } else {
531 // Sign extension.
532 Mask &= SrcTy->getIntegralTypeMask();
533 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
534 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000535
Chris Lattner0157e7f2006-02-11 09:31:47 +0000536 // If the sign bit of the input is known set or clear, then we know the
537 // top bits of the result.
538 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
539 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000540 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000541 KnownOne &= ~NewBits;
542 } else if (KnownOne & InSignBit) { // Input sign bit known set
543 KnownOne |= NewBits;
544 KnownZero &= ~NewBits;
545 } else { // Input sign bit unknown
546 KnownZero &= ~NewBits;
547 KnownOne &= ~NewBits;
548 }
549 }
550 return;
551 }
552 case Instruction::Shl:
553 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
554 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
555 Mask >>= SA->getValue();
556 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
557 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
558 KnownZero <<= SA->getValue();
559 KnownOne <<= SA->getValue();
560 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
561 return;
562 }
563 break;
564 case Instruction::Shr:
565 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
566 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
567 // Compute the new bits that are at the top now.
568 uint64_t HighBits = (1ULL << SA->getValue())-1;
569 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
570
571 if (I->getType()->isUnsigned()) { // Unsigned shift right.
572 Mask <<= SA->getValue();
573 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
574 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
575 KnownZero >>= SA->getValue();
576 KnownOne >>= SA->getValue();
577 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000578 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000579 Mask <<= SA->getValue();
580 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
581 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
582 KnownZero >>= SA->getValue();
583 KnownOne >>= SA->getValue();
584
585 // Handle the sign bits.
586 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
587 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
588
589 if (KnownZero & SignBit) { // New bits are known zero.
590 KnownZero |= HighBits;
591 } else if (KnownOne & SignBit) { // New bits are known one.
592 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000593 }
594 }
595 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000596 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000597 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000598 }
Chris Lattner92a68652006-02-07 08:05:22 +0000599}
600
601/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
602/// this predicate to simplify operations downstream. Mask is known to be zero
603/// for bits that V cannot have.
604static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000605 uint64_t KnownZero, KnownOne;
606 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
607 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
608 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000609}
610
Chris Lattner0157e7f2006-02-11 09:31:47 +0000611/// ShrinkDemandedConstant - Check to see if the specified operand of the
612/// specified instruction is a constant integer. If so, check to see if there
613/// are any bits set in the constant that are not demanded. If so, shrink the
614/// constant and return true.
615static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
616 uint64_t Demanded) {
617 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
618 if (!OpC) return false;
619
620 // If there are no bits set that aren't demanded, nothing to do.
621 if ((~Demanded & OpC->getZExtValue()) == 0)
622 return false;
623
624 // This is producing any bits that are not needed, shrink the RHS.
625 uint64_t Val = Demanded & OpC->getZExtValue();
626 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
627 return true;
628}
629
Chris Lattneree0f2802006-02-12 02:07:56 +0000630// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
631// set of known zero and one bits, compute the maximum and minimum values that
632// could have the specified known zero and known one bits, returning them in
633// min/max.
634static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
635 uint64_t KnownZero,
636 uint64_t KnownOne,
637 int64_t &Min, int64_t &Max) {
638 uint64_t TypeBits = Ty->getIntegralTypeMask();
639 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
640
641 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
642
643 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
644 // bit if it is unknown.
645 Min = KnownOne;
646 Max = KnownOne|UnknownBits;
647
648 if (SignBit & UnknownBits) { // Sign bit is unknown
649 Min |= SignBit;
650 Max &= ~SignBit;
651 }
652
653 // Sign extend the min/max values.
654 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
655 Min = (Min << ShAmt) >> ShAmt;
656 Max = (Max << ShAmt) >> ShAmt;
657}
658
659// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
660// a set of known zero and one bits, compute the maximum and minimum values that
661// could have the specified known zero and known one bits, returning them in
662// min/max.
663static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
664 uint64_t KnownZero,
665 uint64_t KnownOne,
666 uint64_t &Min,
667 uint64_t &Max) {
668 uint64_t TypeBits = Ty->getIntegralTypeMask();
669 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
670
671 // The minimum value is when the unknown bits are all zeros.
672 Min = KnownOne;
673 // The maximum value is when the unknown bits are all ones.
674 Max = KnownOne|UnknownBits;
675}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000676
677
678/// SimplifyDemandedBits - Look at V. At this point, we know that only the
679/// DemandedMask bits of the result of V are ever used downstream. If we can
680/// use this information to simplify V, do so and return true. Otherwise,
681/// analyze the expression and return a mask of KnownOne and KnownZero bits for
682/// the expression (used to simplify the caller). The KnownZero/One bits may
683/// only be accurate for those bits in the DemandedMask.
684bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
685 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000686 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000687 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
688 // We know all of the bits for a constant!
689 KnownOne = CI->getZExtValue() & DemandedMask;
690 KnownZero = ~KnownOne & DemandedMask;
691 return false;
692 }
693
694 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000695 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000696 if (Depth != 0) { // Not at the root.
697 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
698 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000699 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000700 }
Chris Lattner2590e512006-02-07 06:56:34 +0000701 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000702 // just set the DemandedMask to all bits.
703 DemandedMask = V->getType()->getIntegralTypeMask();
704 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000705 if (V != UndefValue::get(V->getType()))
706 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
707 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000708 } else if (Depth == 6) { // Limit search depth.
709 return false;
710 }
711
712 Instruction *I = dyn_cast<Instruction>(V);
713 if (!I) return false; // Only analyze instructions.
714
Chris Lattner0157e7f2006-02-11 09:31:47 +0000715 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000716 switch (I->getOpcode()) {
717 default: break;
718 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000719 // If either the LHS or the RHS are Zero, the result is zero.
720 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
721 KnownZero, KnownOne, Depth+1))
722 return true;
723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
724
725 // If something is known zero on the RHS, the bits aren't demanded on the
726 // LHS.
727 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
728 KnownZero2, KnownOne2, Depth+1))
729 return true;
730 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
731
732 // If all of the demanded bits are known one on one side, return the other.
733 // These bits cannot contribute to the result of the 'and'.
734 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
735 return UpdateValueUsesWith(I, I->getOperand(0));
736 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
737 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000738
739 // If all of the demanded bits in the inputs are known zeros, return zero.
740 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
741 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
742
Chris Lattner0157e7f2006-02-11 09:31:47 +0000743 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000744 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000745 return UpdateValueUsesWith(I, I);
746
747 // Output known-1 bits are only known if set in both the LHS & RHS.
748 KnownOne &= KnownOne2;
749 // Output known-0 are known to be clear if zero in either the LHS | RHS.
750 KnownZero |= KnownZero2;
751 break;
752 case Instruction::Or:
753 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
754 KnownZero, KnownOne, Depth+1))
755 return true;
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
758 KnownZero2, KnownOne2, Depth+1))
759 return true;
760 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
761
762 // If all of the demanded bits are known zero on one side, return the other.
763 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000764 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000765 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000766 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000767 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000768
769 // If all of the potentially set bits on one side are known to be set on
770 // the other side, just use the 'other' side.
771 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
772 (DemandedMask & (~KnownZero)))
773 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000774 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
775 (DemandedMask & (~KnownZero2)))
776 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000777
778 // If the RHS is a constant, see if we can simplify it.
779 if (ShrinkDemandedConstant(I, 1, DemandedMask))
780 return UpdateValueUsesWith(I, I);
781
782 // Output known-0 bits are only known if clear in both the LHS & RHS.
783 KnownZero &= KnownZero2;
784 // Output known-1 are known to be set if set in either the LHS | RHS.
785 KnownOne |= KnownOne2;
786 break;
787 case Instruction::Xor: {
788 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
789 KnownZero, KnownOne, Depth+1))
790 return true;
791 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
792 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
793 KnownZero2, KnownOne2, Depth+1))
794 return true;
795 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
796
797 // If all of the demanded bits are known zero on one side, return the other.
798 // These bits cannot contribute to the result of the 'xor'.
799 if ((DemandedMask & KnownZero) == DemandedMask)
800 return UpdateValueUsesWith(I, I->getOperand(0));
801 if ((DemandedMask & KnownZero2) == DemandedMask)
802 return UpdateValueUsesWith(I, I->getOperand(1));
803
804 // Output known-0 bits are known if clear or set in both the LHS & RHS.
805 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
806 // Output known-1 are known to be set if set in only one of the LHS, RHS.
807 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
808
809 // If all of the unknown bits are known to be zero on one side or the other
810 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000811 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000812 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
813 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
814 Instruction *Or =
815 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
816 I->getName());
817 InsertNewInstBefore(Or, *I);
818 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000819 }
820 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000821
Chris Lattner5b2edb12006-02-12 08:02:11 +0000822 // If all of the demanded bits on one side are known, and all of the set
823 // bits on that side are also known to be set on the other side, turn this
824 // into an AND, as we know the bits will be cleared.
825 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
826 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
827 if ((KnownOne & KnownOne2) == KnownOne) {
828 Constant *AndC = GetConstantInType(I->getType(),
829 ~KnownOne & DemandedMask);
830 Instruction *And =
831 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
832 InsertNewInstBefore(And, *I);
833 return UpdateValueUsesWith(I, And);
834 }
835 }
836
Chris Lattner0157e7f2006-02-11 09:31:47 +0000837 // If the RHS is a constant, see if we can simplify it.
838 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
839 if (ShrinkDemandedConstant(I, 1, DemandedMask))
840 return UpdateValueUsesWith(I, I);
841
842 KnownZero = KnownZeroOut;
843 KnownOne = KnownOneOut;
844 break;
845 }
846 case Instruction::Select:
847 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
848 KnownZero, KnownOne, Depth+1))
849 return true;
850 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
851 KnownZero2, KnownOne2, Depth+1))
852 return true;
853 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
854 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
855
856 // If the operands are constants, see if we can simplify them.
857 if (ShrinkDemandedConstant(I, 1, DemandedMask))
858 return UpdateValueUsesWith(I, I);
859 if (ShrinkDemandedConstant(I, 2, DemandedMask))
860 return UpdateValueUsesWith(I, I);
861
862 // Only known if known in both the LHS and RHS.
863 KnownOne &= KnownOne2;
864 KnownZero &= KnownZero2;
865 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000866 case Instruction::Cast: {
867 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000868 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000869
Chris Lattner0157e7f2006-02-11 09:31:47 +0000870 // If this is an integer truncate or noop, just look in the input.
871 if (SrcTy->getPrimitiveSizeInBits() >=
872 I->getType()->getPrimitiveSizeInBits()) {
873 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
874 KnownZero, KnownOne, Depth+1))
875 return true;
876 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
877 break;
878 }
879
880 // Sign or Zero extension. Compute the bits in the result that are not
881 // present in the input.
882 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
883 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
884
885 // Handle zero extension.
886 if (!SrcTy->isSigned()) {
887 DemandedMask &= SrcTy->getIntegralTypeMask();
888 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
889 KnownZero, KnownOne, Depth+1))
890 return true;
891 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
892 // The top bits are known to be zero.
893 KnownZero |= NewBits;
894 } else {
895 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +0000896 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
897 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
898
899 // If any of the sign extended bits are demanded, we know that the sign
900 // bit is demanded.
901 if (NewBits & DemandedMask)
902 InputDemandedBits |= InSignBit;
903
904 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000905 KnownZero, KnownOne, Depth+1))
906 return true;
907 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
908
909 // If the sign bit of the input is known set or clear, then we know the
910 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +0000911
Chris Lattner0157e7f2006-02-11 09:31:47 +0000912 // If the input sign bit is known zero, or if the NewBits are not demanded
913 // convert this into a zero extension.
914 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +0000915 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000916 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000917 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000918 I->getOperand(0)->getName());
919 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000920 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +0000921 NewVal = new CastInst(NewVal, I->getType(), I->getName());
922 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000923 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000924 } else if (KnownOne & InSignBit) { // Input sign bit known set
925 KnownOne |= NewBits;
926 KnownZero &= ~NewBits;
927 } else { // Input sign bit unknown
928 KnownZero &= ~NewBits;
929 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +0000930 }
Chris Lattner2590e512006-02-07 06:56:34 +0000931 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000932 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000933 }
Chris Lattner2590e512006-02-07 06:56:34 +0000934 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000935 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
936 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
937 KnownZero, KnownOne, Depth+1))
938 return true;
939 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
940 KnownZero <<= SA->getValue();
941 KnownOne <<= SA->getValue();
942 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
943 }
Chris Lattner2590e512006-02-07 06:56:34 +0000944 break;
945 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000946 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
947 unsigned ShAmt = SA->getValue();
948
949 // Compute the new bits that are at the top now.
950 uint64_t HighBits = (1ULL << ShAmt)-1;
951 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +0000952 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000953 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000954 if (SimplifyDemandedBits(I->getOperand(0),
955 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000956 KnownZero, KnownOne, Depth+1))
957 return true;
958 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000959 KnownZero &= TypeMask;
960 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000961 KnownZero >>= ShAmt;
962 KnownOne >>= ShAmt;
963 KnownZero |= HighBits; // high bits known zero.
964 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000965 if (SimplifyDemandedBits(I->getOperand(0),
966 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000967 KnownZero, KnownOne, Depth+1))
968 return true;
969 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000970 KnownZero &= TypeMask;
971 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000972 KnownZero >>= SA->getValue();
973 KnownOne >>= SA->getValue();
974
975 // Handle the sign bits.
976 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
977 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
978
979 // If the input sign bit is known to be zero, or if none of the top bits
980 // are demanded, turn this into an unsigned shift right.
981 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
982 // Convert the input to unsigned.
983 Instruction *NewVal;
984 NewVal = new CastInst(I->getOperand(0),
985 I->getType()->getUnsignedVersion(),
986 I->getOperand(0)->getName());
987 InsertNewInstBefore(NewVal, *I);
988 // Perform the unsigned shift right.
989 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
990 InsertNewInstBefore(NewVal, *I);
991 // Then cast that to the destination type.
992 NewVal = new CastInst(NewVal, I->getType(), I->getName());
993 InsertNewInstBefore(NewVal, *I);
994 return UpdateValueUsesWith(I, NewVal);
995 } else if (KnownOne & SignBit) { // New bits are known one.
996 KnownOne |= HighBits;
997 }
Chris Lattner2590e512006-02-07 06:56:34 +0000998 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000999 }
Chris Lattner2590e512006-02-07 06:56:34 +00001000 break;
1001 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001002
1003 // If the client is only demanding bits that we know, return the known
1004 // constant.
1005 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1006 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001007 return false;
1008}
1009
Chris Lattner623826c2004-09-28 21:48:02 +00001010// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1011// true when both operands are equal...
1012//
1013static bool isTrueWhenEqual(Instruction &I) {
1014 return I.getOpcode() == Instruction::SetEQ ||
1015 I.getOpcode() == Instruction::SetGE ||
1016 I.getOpcode() == Instruction::SetLE;
1017}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001018
1019/// AssociativeOpt - Perform an optimization on an associative operator. This
1020/// function is designed to check a chain of associative operators for a
1021/// potential to apply a certain optimization. Since the optimization may be
1022/// applicable if the expression was reassociated, this checks the chain, then
1023/// reassociates the expression as necessary to expose the optimization
1024/// opportunity. This makes use of a special Functor, which must define
1025/// 'shouldApply' and 'apply' methods.
1026///
1027template<typename Functor>
1028Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1029 unsigned Opcode = Root.getOpcode();
1030 Value *LHS = Root.getOperand(0);
1031
1032 // Quick check, see if the immediate LHS matches...
1033 if (F.shouldApply(LHS))
1034 return F.apply(Root);
1035
1036 // Otherwise, if the LHS is not of the same opcode as the root, return.
1037 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001038 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001039 // Should we apply this transform to the RHS?
1040 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1041
1042 // If not to the RHS, check to see if we should apply to the LHS...
1043 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1044 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1045 ShouldApply = true;
1046 }
1047
1048 // If the functor wants to apply the optimization to the RHS of LHSI,
1049 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1050 if (ShouldApply) {
1051 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001052
Chris Lattnerb8b97502003-08-13 19:01:45 +00001053 // Now all of the instructions are in the current basic block, go ahead
1054 // and perform the reassociation.
1055 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1056
1057 // First move the selected RHS to the LHS of the root...
1058 Root.setOperand(0, LHSI->getOperand(1));
1059
1060 // Make what used to be the LHS of the root be the user of the root...
1061 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001062 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001063 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1064 return 0;
1065 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001066 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001067 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001068 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1069 BasicBlock::iterator ARI = &Root; ++ARI;
1070 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1071 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001072
1073 // Now propagate the ExtraOperand down the chain of instructions until we
1074 // get to LHSI.
1075 while (TmpLHSI != LHSI) {
1076 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001077 // Move the instruction to immediately before the chain we are
1078 // constructing to avoid breaking dominance properties.
1079 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1080 BB->getInstList().insert(ARI, NextLHSI);
1081 ARI = NextLHSI;
1082
Chris Lattnerb8b97502003-08-13 19:01:45 +00001083 Value *NextOp = NextLHSI->getOperand(1);
1084 NextLHSI->setOperand(1, ExtraOperand);
1085 TmpLHSI = NextLHSI;
1086 ExtraOperand = NextOp;
1087 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001088
Chris Lattnerb8b97502003-08-13 19:01:45 +00001089 // Now that the instructions are reassociated, have the functor perform
1090 // the transformation...
1091 return F.apply(Root);
1092 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001093
Chris Lattnerb8b97502003-08-13 19:01:45 +00001094 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1095 }
1096 return 0;
1097}
1098
1099
1100// AddRHS - Implements: X + X --> X << 1
1101struct AddRHS {
1102 Value *RHS;
1103 AddRHS(Value *rhs) : RHS(rhs) {}
1104 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1105 Instruction *apply(BinaryOperator &Add) const {
1106 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1107 ConstantInt::get(Type::UByteTy, 1));
1108 }
1109};
1110
1111// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1112// iff C1&C2 == 0
1113struct AddMaskingAnd {
1114 Constant *C2;
1115 AddMaskingAnd(Constant *c) : C2(c) {}
1116 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001117 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001118 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001119 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001120 }
1121 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001122 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001123 }
1124};
1125
Chris Lattner86102b82005-01-01 16:22:27 +00001126static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001127 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001128 if (isa<CastInst>(I)) {
1129 if (Constant *SOC = dyn_cast<Constant>(SO))
1130 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001131
Chris Lattner86102b82005-01-01 16:22:27 +00001132 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1133 SO->getName() + ".cast"), I);
1134 }
1135
Chris Lattner183b3362004-04-09 19:05:30 +00001136 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001137 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1138 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001139
Chris Lattner183b3362004-04-09 19:05:30 +00001140 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1141 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001142 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1143 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001144 }
1145
1146 Value *Op0 = SO, *Op1 = ConstOperand;
1147 if (!ConstIsRHS)
1148 std::swap(Op0, Op1);
1149 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1151 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1152 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1153 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001154 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001155 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001156 abort();
1157 }
Chris Lattner86102b82005-01-01 16:22:27 +00001158 return IC->InsertNewInstBefore(New, I);
1159}
1160
1161// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1162// constant as the other operand, try to fold the binary operator into the
1163// select arguments. This also works for Cast instructions, which obviously do
1164// not have a second operand.
1165static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1166 InstCombiner *IC) {
1167 // Don't modify shared select instructions
1168 if (!SI->hasOneUse()) return 0;
1169 Value *TV = SI->getOperand(1);
1170 Value *FV = SI->getOperand(2);
1171
1172 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001173 // Bool selects with constant operands can be folded to logical ops.
1174 if (SI->getType() == Type::BoolTy) return 0;
1175
Chris Lattner86102b82005-01-01 16:22:27 +00001176 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1177 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1178
1179 return new SelectInst(SI->getCondition(), SelectTrueVal,
1180 SelectFalseVal);
1181 }
1182 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001183}
1184
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001185
1186/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1187/// node as operand #0, see if we can fold the instruction into the PHI (which
1188/// is only possible if all operands to the PHI are constants).
1189Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1190 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001191 unsigned NumPHIValues = PN->getNumIncomingValues();
1192 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1193 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001194
1195 // Check to see if all of the operands of the PHI are constants. If not, we
1196 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001197 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001198 if (!isa<Constant>(PN->getIncomingValue(i)))
1199 return 0;
1200
1201 // Okay, we can do the transformation: create the new PHI node.
1202 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1203 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001204 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001205 InsertNewInstBefore(NewPN, *PN);
1206
1207 // Next, add all of the operands to the PHI.
1208 if (I.getNumOperands() == 2) {
1209 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001210 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001211 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1212 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1213 PN->getIncomingBlock(i));
1214 }
1215 } else {
1216 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1217 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001218 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001219 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1220 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1221 PN->getIncomingBlock(i));
1222 }
1223 }
1224 return ReplaceInstUsesWith(I, NewPN);
1225}
1226
Chris Lattner113f4f42002-06-25 16:13:24 +00001227Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001228 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001229 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001230
Chris Lattnercf4a9962004-04-10 22:01:55 +00001231 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001232 // X + undef -> undef
1233 if (isa<UndefValue>(RHS))
1234 return ReplaceInstUsesWith(I, RHS);
1235
Chris Lattnercf4a9962004-04-10 22:01:55 +00001236 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001237 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1238 if (RHSC->isNullValue())
1239 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001240 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1241 if (CFP->isExactlyValue(-0.0))
1242 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001243 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001244
Chris Lattnercf4a9962004-04-10 22:01:55 +00001245 // X + (signbit) --> X ^ signbit
1246 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001247 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001248 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001249 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001250 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001251
1252 if (isa<PHINode>(LHS))
1253 if (Instruction *NV = FoldOpIntoPhi(I))
1254 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001255
Chris Lattner330628a2006-01-06 17:59:59 +00001256 ConstantInt *XorRHS = 0;
1257 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001258 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1259 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1260 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1261 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1262
1263 uint64_t C0080Val = 1ULL << 31;
1264 int64_t CFF80Val = -C0080Val;
1265 unsigned Size = 32;
1266 do {
1267 if (TySizeBits > Size) {
1268 bool Found = false;
1269 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1270 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1271 if (RHSSExt == CFF80Val) {
1272 if (XorRHS->getZExtValue() == C0080Val)
1273 Found = true;
1274 } else if (RHSZExt == C0080Val) {
1275 if (XorRHS->getSExtValue() == CFF80Val)
1276 Found = true;
1277 }
1278 if (Found) {
1279 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001280 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001281 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001282 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001283 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001284 Size = 0; // Not a sign ext, but can't be any others either.
1285 goto FoundSExt;
1286 }
1287 }
1288 Size >>= 1;
1289 C0080Val >>= Size;
1290 CFF80Val >>= Size;
1291 } while (Size >= 8);
1292
1293FoundSExt:
1294 const Type *MiddleType = 0;
1295 switch (Size) {
1296 default: break;
1297 case 32: MiddleType = Type::IntTy; break;
1298 case 16: MiddleType = Type::ShortTy; break;
1299 case 8: MiddleType = Type::SByteTy; break;
1300 }
1301 if (MiddleType) {
1302 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1303 InsertNewInstBefore(NewTrunc, I);
1304 return new CastInst(NewTrunc, I.getType());
1305 }
1306 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001307 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001308
Chris Lattnerb8b97502003-08-13 19:01:45 +00001309 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001310 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001311 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001312
1313 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1314 if (RHSI->getOpcode() == Instruction::Sub)
1315 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1316 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1317 }
1318 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1319 if (LHSI->getOpcode() == Instruction::Sub)
1320 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1321 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1322 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001323 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001324
Chris Lattner147e9752002-05-08 22:46:53 +00001325 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001326 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001327 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001328
1329 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001330 if (!isa<Constant>(RHS))
1331 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001332 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001333
Misha Brukmanb1c93172005-04-21 23:48:37 +00001334
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001335 ConstantInt *C2;
1336 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1337 if (X == RHS) // X*C + X --> X * (C+1)
1338 return BinaryOperator::createMul(RHS, AddOne(C2));
1339
1340 // X*C1 + X*C2 --> X * (C1+C2)
1341 ConstantInt *C1;
1342 if (X == dyn_castFoldableMul(RHS, C1))
1343 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001344 }
1345
1346 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001347 if (dyn_castFoldableMul(RHS, C2) == LHS)
1348 return BinaryOperator::createMul(LHS, AddOne(C2));
1349
Chris Lattner57c8d992003-02-18 19:57:07 +00001350
Chris Lattnerb8b97502003-08-13 19:01:45 +00001351 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001352 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001353 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001354
Chris Lattnerb9cde762003-10-02 15:11:26 +00001355 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001356 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001357 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1358 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1359 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001360 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001361
Chris Lattnerbff91d92004-10-08 05:07:56 +00001362 // (X & FF00) + xx00 -> (X+xx00) & FF00
1363 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1364 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1365 if (Anded == CRHS) {
1366 // See if all bits from the first bit set in the Add RHS up are included
1367 // in the mask. First, get the rightmost bit.
1368 uint64_t AddRHSV = CRHS->getRawValue();
1369
1370 // Form a mask of all bits from the lowest bit added through the top.
1371 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001372 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001373
1374 // See if the and mask includes all of these bits.
1375 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001376
Chris Lattnerbff91d92004-10-08 05:07:56 +00001377 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1378 // Okay, the xform is safe. Insert the new add pronto.
1379 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1380 LHS->getName()), I);
1381 return BinaryOperator::createAnd(NewAdd, C2);
1382 }
1383 }
1384 }
1385
Chris Lattnerd4252a72004-07-30 07:50:03 +00001386 // Try to fold constant add into select arguments.
1387 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001388 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001389 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001390 }
1391
Chris Lattner113f4f42002-06-25 16:13:24 +00001392 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001393}
1394
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001395// isSignBit - Return true if the value represented by the constant only has the
1396// highest order bit set.
1397static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001398 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001399 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001400}
1401
Chris Lattner022167f2004-03-13 00:11:49 +00001402/// RemoveNoopCast - Strip off nonconverting casts from the value.
1403///
1404static Value *RemoveNoopCast(Value *V) {
1405 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1406 const Type *CTy = CI->getType();
1407 const Type *OpTy = CI->getOperand(0)->getType();
1408 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001409 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001410 return RemoveNoopCast(CI->getOperand(0));
1411 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1412 return RemoveNoopCast(CI->getOperand(0));
1413 }
1414 return V;
1415}
1416
Chris Lattner113f4f42002-06-25 16:13:24 +00001417Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001418 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001419
Chris Lattnere6794492002-08-12 21:17:25 +00001420 if (Op0 == Op1) // sub X, X -> 0
1421 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001422
Chris Lattnere6794492002-08-12 21:17:25 +00001423 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001424 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001425 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001426
Chris Lattner81a7a232004-10-16 18:11:37 +00001427 if (isa<UndefValue>(Op0))
1428 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1429 if (isa<UndefValue>(Op1))
1430 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1431
Chris Lattner8f2f5982003-11-05 01:06:05 +00001432 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1433 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001434 if (C->isAllOnesValue())
1435 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001436
Chris Lattner8f2f5982003-11-05 01:06:05 +00001437 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001438 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001439 if (match(Op1, m_Not(m_Value(X))))
1440 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001441 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001442 // -((uint)X >> 31) -> ((int)X >> 31)
1443 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001444 if (C->isNullValue()) {
1445 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1446 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001447 if (SI->getOpcode() == Instruction::Shr)
1448 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1449 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001450 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001451 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001452 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001453 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001454 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001455 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001456 // Ok, the transformation is safe. Insert a cast of the incoming
1457 // value, then the new shift, then the new cast.
1458 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1459 SI->getOperand(0)->getName());
1460 Value *InV = InsertNewInstBefore(FirstCast, I);
1461 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1462 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001463 if (NewShift->getType() == I.getType())
1464 return NewShift;
1465 else {
1466 InV = InsertNewInstBefore(NewShift, I);
1467 return new CastInst(NewShift, I.getType());
1468 }
Chris Lattner92295c52004-03-12 23:53:13 +00001469 }
1470 }
Chris Lattner022167f2004-03-13 00:11:49 +00001471 }
Chris Lattner183b3362004-04-09 19:05:30 +00001472
1473 // Try to fold constant sub into select arguments.
1474 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001475 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001476 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001477
1478 if (isa<PHINode>(Op0))
1479 if (Instruction *NV = FoldOpIntoPhi(I))
1480 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001481 }
1482
Chris Lattnera9be4492005-04-07 16:15:25 +00001483 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1484 if (Op1I->getOpcode() == Instruction::Add &&
1485 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001486 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001487 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001488 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001489 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001490 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1491 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1492 // C1-(X+C2) --> (C1-C2)-X
1493 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1494 Op1I->getOperand(0));
1495 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001496 }
1497
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001498 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001499 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1500 // is not used by anyone else...
1501 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001502 if (Op1I->getOpcode() == Instruction::Sub &&
1503 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001504 // Swap the two operands of the subexpr...
1505 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1506 Op1I->setOperand(0, IIOp1);
1507 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001508
Chris Lattner3082c5a2003-02-18 19:28:33 +00001509 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001510 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001511 }
1512
1513 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1514 //
1515 if (Op1I->getOpcode() == Instruction::And &&
1516 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1517 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1518
Chris Lattner396dbfe2004-06-09 05:08:07 +00001519 Value *NewNot =
1520 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001521 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001522 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001523
Chris Lattner0aee4b72004-10-06 15:08:25 +00001524 // -(X sdiv C) -> (X sdiv -C)
1525 if (Op1I->getOpcode() == Instruction::Div)
1526 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001527 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001528 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001529 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001530 ConstantExpr::getNeg(DivRHS));
1531
Chris Lattner57c8d992003-02-18 19:57:07 +00001532 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001533 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001534 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001535 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001536 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001537 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001538 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001539 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001540 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001541
Chris Lattner47060462005-04-07 17:14:51 +00001542 if (!Op0->getType()->isFloatingPoint())
1543 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1544 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001545 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1546 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1547 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1548 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001549 } else if (Op0I->getOpcode() == Instruction::Sub) {
1550 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1551 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001552 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001553
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001554 ConstantInt *C1;
1555 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1556 if (X == Op1) { // X*C - X --> X * (C-1)
1557 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1558 return BinaryOperator::createMul(Op1, CP1);
1559 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001560
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001561 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1562 if (X == dyn_castFoldableMul(Op1, C2))
1563 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1564 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001565 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001566}
1567
Chris Lattnere79e8542004-02-23 06:38:22 +00001568/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1569/// really just returns true if the most significant (sign) bit is set.
1570static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1571 if (RHS->getType()->isSigned()) {
1572 // True if source is LHS < 0 or LHS <= -1
1573 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1574 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1575 } else {
1576 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1577 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1578 // the size of the integer type.
1579 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001580 return RHSC->getValue() ==
1581 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001582 if (Opcode == Instruction::SetGT)
1583 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001584 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001585 }
1586 return false;
1587}
1588
Chris Lattner113f4f42002-06-25 16:13:24 +00001589Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001590 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001591 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001592
Chris Lattner81a7a232004-10-16 18:11:37 +00001593 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1595
Chris Lattnere6794492002-08-12 21:17:25 +00001596 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001597 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1598 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001599
1600 // ((X << C1)*C2) == (X * (C2 << C1))
1601 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1602 if (SI->getOpcode() == Instruction::Shl)
1603 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001604 return BinaryOperator::createMul(SI->getOperand(0),
1605 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001606
Chris Lattnercce81be2003-09-11 22:24:54 +00001607 if (CI->isNullValue())
1608 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1609 if (CI->equalsInt(1)) // X * 1 == X
1610 return ReplaceInstUsesWith(I, Op0);
1611 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001612 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001613
Chris Lattnercce81be2003-09-11 22:24:54 +00001614 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001615 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1616 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001617 return new ShiftInst(Instruction::Shl, Op0,
1618 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001619 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001620 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001621 if (Op1F->isNullValue())
1622 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001623
Chris Lattner3082c5a2003-02-18 19:28:33 +00001624 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1625 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1626 if (Op1F->getValue() == 1.0)
1627 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1628 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001629
1630 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1631 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1632 isa<ConstantInt>(Op0I->getOperand(1))) {
1633 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1634 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1635 Op1, "tmp");
1636 InsertNewInstBefore(Add, I);
1637 Value *C1C2 = ConstantExpr::getMul(Op1,
1638 cast<Constant>(Op0I->getOperand(1)));
1639 return BinaryOperator::createAdd(Add, C1C2);
1640
1641 }
Chris Lattner183b3362004-04-09 19:05:30 +00001642
1643 // Try to fold constant mul into select arguments.
1644 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001645 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001646 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001647
1648 if (isa<PHINode>(Op0))
1649 if (Instruction *NV = FoldOpIntoPhi(I))
1650 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001651 }
1652
Chris Lattner934a64cf2003-03-10 23:23:04 +00001653 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1654 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001655 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001656
Chris Lattner2635b522004-02-23 05:39:21 +00001657 // If one of the operands of the multiply is a cast from a boolean value, then
1658 // we know the bool is either zero or one, so this is a 'masking' multiply.
1659 // See if we can simplify things based on how the boolean was originally
1660 // formed.
1661 CastInst *BoolCast = 0;
1662 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1663 if (CI->getOperand(0)->getType() == Type::BoolTy)
1664 BoolCast = CI;
1665 if (!BoolCast)
1666 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1667 if (CI->getOperand(0)->getType() == Type::BoolTy)
1668 BoolCast = CI;
1669 if (BoolCast) {
1670 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1671 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1672 const Type *SCOpTy = SCIOp0->getType();
1673
Chris Lattnere79e8542004-02-23 06:38:22 +00001674 // If the setcc is true iff the sign bit of X is set, then convert this
1675 // multiply into a shift/and combination.
1676 if (isa<ConstantInt>(SCIOp1) &&
1677 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001678 // Shift the X value right to turn it into "all signbits".
1679 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001680 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001681 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001682 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001683 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1684 SCIOp0->getName()), I);
1685 }
1686
1687 Value *V =
1688 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1689 BoolCast->getOperand(0)->getName()+
1690 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001691
1692 // If the multiply type is not the same as the source type, sign extend
1693 // or truncate to the multiply type.
1694 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001695 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001696
Chris Lattner2635b522004-02-23 05:39:21 +00001697 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001698 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001699 }
1700 }
1701 }
1702
Chris Lattner113f4f42002-06-25 16:13:24 +00001703 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001704}
1705
Chris Lattner113f4f42002-06-25 16:13:24 +00001706Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001708
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001709 if (isa<UndefValue>(Op0)) // undef / X -> 0
1710 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1711 if (isa<UndefValue>(Op1))
1712 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1713
1714 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001715 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001716 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001717 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001718
Chris Lattnere20c3342004-04-26 14:01:59 +00001719 // div X, -1 == -X
1720 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001721 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001722
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001723 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001724 if (LHS->getOpcode() == Instruction::Div)
1725 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001726 // (X / C1) / C2 -> X / (C1*C2)
1727 return BinaryOperator::createDiv(LHS->getOperand(0),
1728 ConstantExpr::getMul(RHS, LHSRHS));
1729 }
1730
Chris Lattner3082c5a2003-02-18 19:28:33 +00001731 // Check to see if this is an unsigned division with an exact power of 2,
1732 // if so, convert to a right shift.
1733 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1734 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001735 if (isPowerOf2_64(Val)) {
1736 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001737 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001738 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001739 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001740
Chris Lattner4ad08352004-10-09 02:50:40 +00001741 // -X/C -> X/-C
1742 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001743 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001744 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1745
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001746 if (!RHS->isNullValue()) {
1747 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001748 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001749 return R;
1750 if (isa<PHINode>(Op0))
1751 if (Instruction *NV = FoldOpIntoPhi(I))
1752 return NV;
1753 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001754 }
1755
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001756 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1757 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1758 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1759 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1760 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1761 if (STO->getValue() == 0) { // Couldn't be this argument.
1762 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001763 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001764 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001765 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001766 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001767 }
1768
Chris Lattner42362612005-04-08 04:03:26 +00001769 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001770 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1771 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001772 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1773 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1774 TC, SI->getName()+".t");
1775 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001776
Chris Lattner42362612005-04-08 04:03:26 +00001777 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1778 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1779 FC, SI->getName()+".f");
1780 FSI = InsertNewInstBefore(FSI, I);
1781 return new SelectInst(SI->getOperand(0), TSI, FSI);
1782 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001783 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001784
Chris Lattner3082c5a2003-02-18 19:28:33 +00001785 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001786 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001787 if (LHS->equalsInt(0))
1788 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1789
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001790 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001791 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001792 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001793 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1794 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001795 const Type *NTy = Op0->getType()->getUnsignedVersion();
1796 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1797 InsertNewInstBefore(LHS, I);
1798 Value *RHS;
1799 if (Constant *R = dyn_cast<Constant>(Op1))
1800 RHS = ConstantExpr::getCast(R, NTy);
1801 else
1802 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1803 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1804 InsertNewInstBefore(Div, I);
1805 return new CastInst(Div, I.getType());
1806 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001807 } else {
1808 // Known to be an unsigned division.
1809 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1810 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1811 if (RHSI->getOpcode() == Instruction::Shl &&
1812 isa<ConstantUInt>(RHSI->getOperand(0))) {
1813 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1814 if (isPowerOf2_64(C1)) {
1815 unsigned C2 = Log2_64(C1);
1816 Value *Add = RHSI->getOperand(1);
1817 if (C2) {
1818 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1819 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1820 "tmp"), I);
1821 }
1822 return new ShiftInst(Instruction::Shr, Op0, Add);
1823 }
1824 }
1825 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001826 }
1827
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001828 return 0;
1829}
1830
1831
Chris Lattner85dda9a2006-03-02 06:50:58 +00001832/// GetFactor - If we can prove that the specified value is at least a multiple
1833/// of some factor, return that factor.
1834static Constant *GetFactor(Value *V) {
1835 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1836 return CI;
1837
1838 // Unless we can be tricky, we know this is a multiple of 1.
1839 Constant *Result = ConstantInt::get(V->getType(), 1);
1840
1841 Instruction *I = dyn_cast<Instruction>(V);
1842 if (!I) return Result;
1843
1844 if (I->getOpcode() == Instruction::Mul) {
1845 // Handle multiplies by a constant, etc.
1846 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1847 GetFactor(I->getOperand(1)));
1848 } else if (I->getOpcode() == Instruction::Shl) {
1849 // (X<<C) -> X * (1 << C)
1850 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1851 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1852 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1853 }
1854 } else if (I->getOpcode() == Instruction::And) {
1855 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1856 // X & 0xFFF0 is known to be a multiple of 16.
1857 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1858 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1859 return ConstantExpr::getShl(Result,
1860 ConstantUInt::get(Type::UByteTy, Zeros));
1861 }
1862 } else if (I->getOpcode() == Instruction::Cast) {
1863 Value *Op = I->getOperand(0);
1864 // Only handle int->int casts.
1865 if (!Op->getType()->isInteger()) return Result;
1866 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1867 }
1868 return Result;
1869}
1870
Chris Lattner113f4f42002-06-25 16:13:24 +00001871Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001872 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001873
1874 // 0 % X == 0, we don't need to preserve faults!
1875 if (Constant *LHS = dyn_cast<Constant>(Op0))
1876 if (LHS->isNullValue())
1877 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1878
1879 if (isa<UndefValue>(Op0)) // undef % X -> 0
1880 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1881 if (isa<UndefValue>(Op1))
1882 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1883
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001884 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001885 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001886 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001887 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001888 // X % -Y -> X % Y
1889 AddUsesToWorkList(I);
1890 I.setOperand(1, RHSNeg);
1891 return &I;
1892 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001893
1894 // If the top bits of both operands are zero (i.e. we can prove they are
1895 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001896 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1897 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001898 const Type *NTy = Op0->getType()->getUnsignedVersion();
1899 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1900 InsertNewInstBefore(LHS, I);
1901 Value *RHS;
1902 if (Constant *R = dyn_cast<Constant>(Op1))
1903 RHS = ConstantExpr::getCast(R, NTy);
1904 else
1905 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1906 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1907 InsertNewInstBefore(Rem, I);
1908 return new CastInst(Rem, I.getType());
1909 }
1910 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001911
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001912 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001913 // X % 0 == undef, we don't need to preserve faults!
1914 if (RHS->equalsInt(0))
1915 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1916
Chris Lattner3082c5a2003-02-18 19:28:33 +00001917 if (RHS->equalsInt(1)) // X % 1 == 0
1918 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1919
1920 // Check to see if this is an unsigned remainder with an exact power of 2,
1921 // if so, convert to a bitwise and.
1922 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001923 if (isPowerOf2_64(C->getValue()))
1924 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001925
Chris Lattnerb70f1412006-02-28 05:49:21 +00001926 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1927 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1928 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1929 return R;
1930 } else if (isa<PHINode>(Op0I)) {
1931 if (Instruction *NV = FoldOpIntoPhi(I))
1932 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00001933 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00001934
1935 // X*C1%C2 --> 0 iff C1%C2 == 0
1936 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1937 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00001938 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001939 }
1940
Chris Lattner2e90b732006-02-05 07:54:04 +00001941 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1942 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1943 if (I.getType()->isUnsigned() &&
1944 RHSI->getOpcode() == Instruction::Shl &&
1945 isa<ConstantUInt>(RHSI->getOperand(0))) {
1946 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1947 if (isPowerOf2_64(C1)) {
1948 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1949 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1950 "tmp"), I);
1951 return BinaryOperator::createAnd(Op0, Add);
1952 }
1953 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001954
1955 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1956 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1957 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1958 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1959 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1960 if (STO->getValue() == 0) { // Couldn't be this argument.
1961 I.setOperand(1, SFO);
1962 return &I;
1963 } else if (SFO->getValue() == 0) {
1964 I.setOperand(1, STO);
1965 return &I;
1966 }
1967
1968 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1969 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1970 SubOne(STO), SI->getName()+".t"), I);
1971 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1972 SubOne(SFO), SI->getName()+".f"), I);
1973 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1974 }
1975 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001976 }
1977
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001978 return 0;
1979}
1980
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001981// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001982static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001983 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1984 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001985
1986 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001987
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001988 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001989 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001990 int64_t Val = INT64_MAX; // All ones
1991 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1992 return CS->getValue() == Val-1;
1993}
1994
1995// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001996static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001997 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1998 return CU->getValue() == 1;
1999
2000 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002001
2002 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002003 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002004 int64_t Val = -1; // All ones
2005 Val <<= TypeBits-1; // Shift over to the right spot
2006 return CS->getValue() == Val+1;
2007}
2008
Chris Lattner35167c32004-06-09 07:59:58 +00002009// isOneBitSet - Return true if there is exactly one bit set in the specified
2010// constant.
2011static bool isOneBitSet(const ConstantInt *CI) {
2012 uint64_t V = CI->getRawValue();
2013 return V && (V & (V-1)) == 0;
2014}
2015
Chris Lattner8fc5af42004-09-23 21:46:38 +00002016#if 0 // Currently unused
2017// isLowOnes - Return true if the constant is of the form 0+1+.
2018static bool isLowOnes(const ConstantInt *CI) {
2019 uint64_t V = CI->getRawValue();
2020
2021 // There won't be bits set in parts that the type doesn't contain.
2022 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2023
2024 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2025 return U && V && (U & V) == 0;
2026}
2027#endif
2028
2029// isHighOnes - Return true if the constant is of the form 1+0+.
2030// This is the same as lowones(~X).
2031static bool isHighOnes(const ConstantInt *CI) {
2032 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002033 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002034
2035 // There won't be bits set in parts that the type doesn't contain.
2036 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2037
2038 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2039 return U && V && (U & V) == 0;
2040}
2041
2042
Chris Lattner3ac7c262003-08-13 20:16:26 +00002043/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2044/// are carefully arranged to allow folding of expressions such as:
2045///
2046/// (A < B) | (A > B) --> (A != B)
2047///
2048/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2049/// represents that the comparison is true if A == B, and bit value '1' is true
2050/// if A < B.
2051///
2052static unsigned getSetCondCode(const SetCondInst *SCI) {
2053 switch (SCI->getOpcode()) {
2054 // False -> 0
2055 case Instruction::SetGT: return 1;
2056 case Instruction::SetEQ: return 2;
2057 case Instruction::SetGE: return 3;
2058 case Instruction::SetLT: return 4;
2059 case Instruction::SetNE: return 5;
2060 case Instruction::SetLE: return 6;
2061 // True -> 7
2062 default:
2063 assert(0 && "Invalid SetCC opcode!");
2064 return 0;
2065 }
2066}
2067
2068/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2069/// opcode and two operands into either a constant true or false, or a brand new
2070/// SetCC instruction.
2071static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2072 switch (Opcode) {
2073 case 0: return ConstantBool::False;
2074 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2075 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2076 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2077 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2078 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2079 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2080 case 7: return ConstantBool::True;
2081 default: assert(0 && "Illegal SetCCCode!"); return 0;
2082 }
2083}
2084
2085// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2086struct FoldSetCCLogical {
2087 InstCombiner &IC;
2088 Value *LHS, *RHS;
2089 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2090 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2091 bool shouldApply(Value *V) const {
2092 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2093 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2094 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2095 return false;
2096 }
2097 Instruction *apply(BinaryOperator &Log) const {
2098 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2099 if (SCI->getOperand(0) != LHS) {
2100 assert(SCI->getOperand(1) == LHS);
2101 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2102 }
2103
2104 unsigned LHSCode = getSetCondCode(SCI);
2105 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2106 unsigned Code;
2107 switch (Log.getOpcode()) {
2108 case Instruction::And: Code = LHSCode & RHSCode; break;
2109 case Instruction::Or: Code = LHSCode | RHSCode; break;
2110 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002111 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002112 }
2113
2114 Value *RV = getSetCCValue(Code, LHS, RHS);
2115 if (Instruction *I = dyn_cast<Instruction>(RV))
2116 return I;
2117 // Otherwise, it's a constant boolean value...
2118 return IC.ReplaceInstUsesWith(Log, RV);
2119 }
2120};
2121
Chris Lattnerba1cb382003-09-19 17:17:26 +00002122// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2123// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2124// guaranteed to be either a shift instruction or a binary operator.
2125Instruction *InstCombiner::OptAndOp(Instruction *Op,
2126 ConstantIntegral *OpRHS,
2127 ConstantIntegral *AndRHS,
2128 BinaryOperator &TheAnd) {
2129 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002130 Constant *Together = 0;
2131 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002132 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002133
Chris Lattnerba1cb382003-09-19 17:17:26 +00002134 switch (Op->getOpcode()) {
2135 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002136 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002137 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2138 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002139 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002140 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002141 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002142 }
2143 break;
2144 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002145 if (Together == AndRHS) // (X | C) & C --> C
2146 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002147
Chris Lattner86102b82005-01-01 16:22:27 +00002148 if (Op->hasOneUse() && Together != OpRHS) {
2149 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2150 std::string Op0Name = Op->getName(); Op->setName("");
2151 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2152 InsertNewInstBefore(Or, TheAnd);
2153 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002154 }
2155 break;
2156 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002157 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002158 // Adding a one to a single bit bit-field should be turned into an XOR
2159 // of the bit. First thing to check is to see if this AND is with a
2160 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002161 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002162
2163 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002164 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002165
2166 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002167 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002168 // Ok, at this point, we know that we are masking the result of the
2169 // ADD down to exactly one bit. If the constant we are adding has
2170 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002171 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002172
Chris Lattnerba1cb382003-09-19 17:17:26 +00002173 // Check to see if any bits below the one bit set in AndRHSV are set.
2174 if ((AddRHS & (AndRHSV-1)) == 0) {
2175 // If not, the only thing that can effect the output of the AND is
2176 // the bit specified by AndRHSV. If that bit is set, the effect of
2177 // the XOR is to toggle the bit. If it is clear, then the ADD has
2178 // no effect.
2179 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2180 TheAnd.setOperand(0, X);
2181 return &TheAnd;
2182 } else {
2183 std::string Name = Op->getName(); Op->setName("");
2184 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002185 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002186 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002187 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002188 }
2189 }
2190 }
2191 }
2192 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002193
2194 case Instruction::Shl: {
2195 // We know that the AND will not produce any of the bits shifted in, so if
2196 // the anded constant includes them, clear them now!
2197 //
2198 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002199 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2200 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002201
Chris Lattner7e794272004-09-24 15:21:34 +00002202 if (CI == ShlMask) { // Masking out bits that the shift already masks
2203 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2204 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002205 TheAnd.setOperand(1, CI);
2206 return &TheAnd;
2207 }
2208 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002209 }
Chris Lattner2da29172003-09-19 19:05:02 +00002210 case Instruction::Shr:
2211 // We know that the AND will not produce any of the bits shifted in, so if
2212 // the anded constant includes them, clear them now! This only applies to
2213 // unsigned shifts, because a signed shr may bring in set bits!
2214 //
2215 if (AndRHS->getType()->isUnsigned()) {
2216 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002217 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2218 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2219
2220 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2221 return ReplaceInstUsesWith(TheAnd, Op);
2222 } else if (CI != AndRHS) {
2223 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002224 return &TheAnd;
2225 }
Chris Lattner7e794272004-09-24 15:21:34 +00002226 } else { // Signed shr.
2227 // See if this is shifting in some sign extension, then masking it out
2228 // with an and.
2229 if (Op->hasOneUse()) {
2230 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2231 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2232 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002233 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002234 // Make the argument unsigned.
2235 Value *ShVal = Op->getOperand(0);
2236 ShVal = InsertCastBefore(ShVal,
2237 ShVal->getType()->getUnsignedVersion(),
2238 TheAnd);
2239 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2240 OpRHS, Op->getName()),
2241 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002242 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2243 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2244 TheAnd.getName()),
2245 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002246 return new CastInst(ShVal, Op->getType());
2247 }
2248 }
Chris Lattner2da29172003-09-19 19:05:02 +00002249 }
2250 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002251 }
2252 return 0;
2253}
2254
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002255
Chris Lattner6862fbd2004-09-29 17:40:11 +00002256/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2257/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2258/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2259/// insert new instructions.
2260Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2261 bool Inside, Instruction &IB) {
2262 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2263 "Lo is not <= Hi in range emission code!");
2264 if (Inside) {
2265 if (Lo == Hi) // Trivially false.
2266 return new SetCondInst(Instruction::SetNE, V, V);
2267 if (cast<ConstantIntegral>(Lo)->isMinValue())
2268 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002269
Chris Lattner6862fbd2004-09-29 17:40:11 +00002270 Constant *AddCST = ConstantExpr::getNeg(Lo);
2271 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2272 InsertNewInstBefore(Add, IB);
2273 // Convert to unsigned for the comparison.
2274 const Type *UnsType = Add->getType()->getUnsignedVersion();
2275 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2276 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2277 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2278 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2279 }
2280
2281 if (Lo == Hi) // Trivially true.
2282 return new SetCondInst(Instruction::SetEQ, V, V);
2283
2284 Hi = SubOne(cast<ConstantInt>(Hi));
2285 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2286 return new SetCondInst(Instruction::SetGT, V, Hi);
2287
2288 // Emit X-Lo > Hi-Lo-1
2289 Constant *AddCST = ConstantExpr::getNeg(Lo);
2290 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2291 InsertNewInstBefore(Add, IB);
2292 // Convert to unsigned for the comparison.
2293 const Type *UnsType = Add->getType()->getUnsignedVersion();
2294 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2295 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2296 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2297 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2298}
2299
Chris Lattnerb4b25302005-09-18 07:22:02 +00002300// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2301// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2302// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2303// not, since all 1s are not contiguous.
2304static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2305 uint64_t V = Val->getRawValue();
2306 if (!isShiftedMask_64(V)) return false;
2307
2308 // look for the first zero bit after the run of ones
2309 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2310 // look for the first non-zero bit
2311 ME = 64-CountLeadingZeros_64(V);
2312 return true;
2313}
2314
2315
2316
2317/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2318/// where isSub determines whether the operator is a sub. If we can fold one of
2319/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002320///
2321/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2322/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2323/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2324///
2325/// return (A +/- B).
2326///
2327Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2328 ConstantIntegral *Mask, bool isSub,
2329 Instruction &I) {
2330 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2331 if (!LHSI || LHSI->getNumOperands() != 2 ||
2332 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2333
2334 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2335
2336 switch (LHSI->getOpcode()) {
2337 default: return 0;
2338 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002339 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2340 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2341 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2342 break;
2343
2344 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2345 // part, we don't need any explicit masks to take them out of A. If that
2346 // is all N is, ignore it.
2347 unsigned MB, ME;
2348 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002349 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2350 Mask >>= 64-MB+1;
2351 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002352 break;
2353 }
2354 }
Chris Lattneraf517572005-09-18 04:24:45 +00002355 return 0;
2356 case Instruction::Or:
2357 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002358 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2359 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2360 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002361 break;
2362 return 0;
2363 }
2364
2365 Instruction *New;
2366 if (isSub)
2367 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2368 else
2369 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2370 return InsertNewInstBefore(New, I);
2371}
2372
Chris Lattner113f4f42002-06-25 16:13:24 +00002373Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002374 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002375 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002376
Chris Lattner81a7a232004-10-16 18:11:37 +00002377 if (isa<UndefValue>(Op1)) // X & undef -> 0
2378 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2379
Chris Lattner86102b82005-01-01 16:22:27 +00002380 // and X, X = X
2381 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002382 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002383
Chris Lattner5b2edb12006-02-12 08:02:11 +00002384 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002385 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002386 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002387 if (!isa<PackedType>(I.getType()) &&
2388 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002389 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002390 return &I;
2391
Chris Lattner86102b82005-01-01 16:22:27 +00002392 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002393 uint64_t AndRHSMask = AndRHS->getZExtValue();
2394 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002395 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002396
Chris Lattnerba1cb382003-09-19 17:17:26 +00002397 // Optimize a variety of ((val OP C1) & C2) combinations...
2398 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2399 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002400 Value *Op0LHS = Op0I->getOperand(0);
2401 Value *Op0RHS = Op0I->getOperand(1);
2402 switch (Op0I->getOpcode()) {
2403 case Instruction::Xor:
2404 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002405 // If the mask is only needed on one incoming arm, push it up.
2406 if (Op0I->hasOneUse()) {
2407 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2408 // Not masking anything out for the LHS, move to RHS.
2409 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2410 Op0RHS->getName()+".masked");
2411 InsertNewInstBefore(NewRHS, I);
2412 return BinaryOperator::create(
2413 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002414 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002415 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002416 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2417 // Not masking anything out for the RHS, move to LHS.
2418 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2419 Op0LHS->getName()+".masked");
2420 InsertNewInstBefore(NewLHS, I);
2421 return BinaryOperator::create(
2422 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2423 }
2424 }
2425
Chris Lattner86102b82005-01-01 16:22:27 +00002426 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002427 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002428 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2429 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2430 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2431 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2432 return BinaryOperator::createAnd(V, AndRHS);
2433 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2434 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002435 break;
2436
2437 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002438 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2439 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2440 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2441 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2442 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002443 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002444 }
2445
Chris Lattner16464b32003-07-23 19:25:52 +00002446 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002447 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002448 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002449 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2450 const Type *SrcTy = CI->getOperand(0)->getType();
2451
Chris Lattner2c14cf72005-08-07 07:03:10 +00002452 // If this is an integer truncation or change from signed-to-unsigned, and
2453 // if the source is an and/or with immediate, transform it. This
2454 // frequently occurs for bitfield accesses.
2455 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2456 if (SrcTy->getPrimitiveSizeInBits() >=
2457 I.getType()->getPrimitiveSizeInBits() &&
2458 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002459 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002460 if (CastOp->getOpcode() == Instruction::And) {
2461 // Change: and (cast (and X, C1) to T), C2
2462 // into : and (cast X to T), trunc(C1)&C2
2463 // This will folds the two ands together, which may allow other
2464 // simplifications.
2465 Instruction *NewCast =
2466 new CastInst(CastOp->getOperand(0), I.getType(),
2467 CastOp->getName()+".shrunk");
2468 NewCast = InsertNewInstBefore(NewCast, I);
2469
2470 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2471 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2472 return BinaryOperator::createAnd(NewCast, C3);
2473 } else if (CastOp->getOpcode() == Instruction::Or) {
2474 // Change: and (cast (or X, C1) to T), C2
2475 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2476 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2477 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2478 return ReplaceInstUsesWith(I, AndRHS);
2479 }
2480 }
Chris Lattner33217db2003-07-23 19:36:21 +00002481 }
Chris Lattner183b3362004-04-09 19:05:30 +00002482
2483 // Try to fold constant and into select arguments.
2484 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002485 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002486 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002487 if (isa<PHINode>(Op0))
2488 if (Instruction *NV = FoldOpIntoPhi(I))
2489 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002490 }
2491
Chris Lattnerbb74e222003-03-10 23:06:50 +00002492 Value *Op0NotVal = dyn_castNotVal(Op0);
2493 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002494
Chris Lattner023a4832004-06-18 06:07:51 +00002495 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2496 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2497
Misha Brukman9c003d82004-07-30 12:50:08 +00002498 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002499 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002500 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2501 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002502 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002503 return BinaryOperator::createNot(Or);
2504 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002505
2506 {
2507 Value *A = 0, *B = 0;
2508 ConstantInt *C1 = 0, *C2 = 0;
2509 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2510 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2511 return ReplaceInstUsesWith(I, Op1);
2512 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2513 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2514 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002515
2516 if (Op0->hasOneUse() &&
2517 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2518 if (A == Op1) { // (A^B)&A -> A&(A^B)
2519 I.swapOperands(); // Simplify below
2520 std::swap(Op0, Op1);
2521 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2522 cast<BinaryOperator>(Op0)->swapOperands();
2523 I.swapOperands(); // Simplify below
2524 std::swap(Op0, Op1);
2525 }
2526 }
2527 if (Op1->hasOneUse() &&
2528 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2529 if (B == Op0) { // B&(A^B) -> B&(B^A)
2530 cast<BinaryOperator>(Op1)->swapOperands();
2531 std::swap(A, B);
2532 }
2533 if (A == Op0) { // A&(A^B) -> A & ~B
2534 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2535 InsertNewInstBefore(NotB, I);
2536 return BinaryOperator::createAnd(A, NotB);
2537 }
2538 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002539 }
2540
Chris Lattner3082c5a2003-02-18 19:28:33 +00002541
Chris Lattner623826c2004-09-28 21:48:02 +00002542 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2543 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002544 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2545 return R;
2546
Chris Lattner623826c2004-09-28 21:48:02 +00002547 Value *LHSVal, *RHSVal;
2548 ConstantInt *LHSCst, *RHSCst;
2549 Instruction::BinaryOps LHSCC, RHSCC;
2550 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2551 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2552 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2553 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002554 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002555 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2556 // Ensure that the larger constant is on the RHS.
2557 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2558 SetCondInst *LHS = cast<SetCondInst>(Op0);
2559 if (cast<ConstantBool>(Cmp)->getValue()) {
2560 std::swap(LHS, RHS);
2561 std::swap(LHSCst, RHSCst);
2562 std::swap(LHSCC, RHSCC);
2563 }
2564
2565 // At this point, we know we have have two setcc instructions
2566 // comparing a value against two constants and and'ing the result
2567 // together. Because of the above check, we know that we only have
2568 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2569 // FoldSetCCLogical check above), that the two constants are not
2570 // equal.
2571 assert(LHSCst != RHSCst && "Compares not folded above?");
2572
2573 switch (LHSCC) {
2574 default: assert(0 && "Unknown integer condition code!");
2575 case Instruction::SetEQ:
2576 switch (RHSCC) {
2577 default: assert(0 && "Unknown integer condition code!");
2578 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2579 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2580 return ReplaceInstUsesWith(I, ConstantBool::False);
2581 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2582 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2583 return ReplaceInstUsesWith(I, LHS);
2584 }
2585 case Instruction::SetNE:
2586 switch (RHSCC) {
2587 default: assert(0 && "Unknown integer condition code!");
2588 case Instruction::SetLT:
2589 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2590 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2591 break; // (X != 13 & X < 15) -> no change
2592 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2593 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2594 return ReplaceInstUsesWith(I, RHS);
2595 case Instruction::SetNE:
2596 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2597 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2598 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2599 LHSVal->getName()+".off");
2600 InsertNewInstBefore(Add, I);
2601 const Type *UnsType = Add->getType()->getUnsignedVersion();
2602 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2603 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2604 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2605 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2606 }
2607 break; // (X != 13 & X != 15) -> no change
2608 }
2609 break;
2610 case Instruction::SetLT:
2611 switch (RHSCC) {
2612 default: assert(0 && "Unknown integer condition code!");
2613 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2614 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2615 return ReplaceInstUsesWith(I, ConstantBool::False);
2616 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2617 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2618 return ReplaceInstUsesWith(I, LHS);
2619 }
2620 case Instruction::SetGT:
2621 switch (RHSCC) {
2622 default: assert(0 && "Unknown integer condition code!");
2623 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2624 return ReplaceInstUsesWith(I, LHS);
2625 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2626 return ReplaceInstUsesWith(I, RHS);
2627 case Instruction::SetNE:
2628 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2629 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2630 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002631 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2632 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002633 }
2634 }
2635 }
2636 }
2637
Chris Lattner113f4f42002-06-25 16:13:24 +00002638 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002639}
2640
Chris Lattner113f4f42002-06-25 16:13:24 +00002641Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002642 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002644
Chris Lattner81a7a232004-10-16 18:11:37 +00002645 if (isa<UndefValue>(Op1))
2646 return ReplaceInstUsesWith(I, // X | undef -> -1
2647 ConstantIntegral::getAllOnesValue(I.getType()));
2648
Chris Lattner5b2edb12006-02-12 08:02:11 +00002649 // or X, X = X
2650 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002651 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002652
Chris Lattner5b2edb12006-02-12 08:02:11 +00002653 // See if we can simplify any instructions used by the instruction whose sole
2654 // purpose is to compute bits we don't care about.
2655 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002656 if (!isa<PackedType>(I.getType()) &&
2657 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002658 KnownZero, KnownOne))
2659 return &I;
2660
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002661 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002662 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002663 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002664 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2665 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002666 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2667 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002668 InsertNewInstBefore(Or, I);
2669 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2670 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002671
Chris Lattnerd4252a72004-07-30 07:50:03 +00002672 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2673 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2674 std::string Op0Name = Op0->getName(); Op0->setName("");
2675 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2676 InsertNewInstBefore(Or, I);
2677 return BinaryOperator::createXor(Or,
2678 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002679 }
Chris Lattner183b3362004-04-09 19:05:30 +00002680
2681 // Try to fold constant and into select arguments.
2682 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002683 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002684 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002685 if (isa<PHINode>(Op0))
2686 if (Instruction *NV = FoldOpIntoPhi(I))
2687 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002688 }
2689
Chris Lattner330628a2006-01-06 17:59:59 +00002690 Value *A = 0, *B = 0;
2691 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002692
2693 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2694 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2695 return ReplaceInstUsesWith(I, Op1);
2696 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2697 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2698 return ReplaceInstUsesWith(I, Op0);
2699
Chris Lattnerb62f5082005-05-09 04:58:36 +00002700 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2701 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002702 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002703 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2704 Op0->setName("");
2705 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2706 }
2707
2708 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2709 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002710 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002711 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2712 Op0->setName("");
2713 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2714 }
2715
Chris Lattner15212982005-09-18 03:42:07 +00002716 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002717 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002718 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2719
2720 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2721 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2722
2723
Chris Lattner01f56c62005-09-18 06:02:59 +00002724 // If we have: ((V + N) & C1) | (V & C2)
2725 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2726 // replace with V+N.
2727 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002728 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002729 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2730 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2731 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002732 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002733 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002734 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002735 return ReplaceInstUsesWith(I, A);
2736 }
2737 // Or commutes, try both ways.
2738 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2739 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2740 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002741 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002742 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002743 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002744 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002745 }
2746 }
2747 }
Chris Lattner812aab72003-08-12 19:11:07 +00002748
Chris Lattnerd4252a72004-07-30 07:50:03 +00002749 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2750 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002751 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002752 ConstantIntegral::getAllOnesValue(I.getType()));
2753 } else {
2754 A = 0;
2755 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002756 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002757 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2758 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002759 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002760 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002761
Misha Brukman9c003d82004-07-30 12:50:08 +00002762 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002763 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2764 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2765 I.getName()+".demorgan"), I);
2766 return BinaryOperator::createNot(And);
2767 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002768 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002769
Chris Lattner3ac7c262003-08-13 20:16:26 +00002770 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002771 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002772 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2773 return R;
2774
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002775 Value *LHSVal, *RHSVal;
2776 ConstantInt *LHSCst, *RHSCst;
2777 Instruction::BinaryOps LHSCC, RHSCC;
2778 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2779 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2780 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2781 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002782 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002783 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2784 // Ensure that the larger constant is on the RHS.
2785 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2786 SetCondInst *LHS = cast<SetCondInst>(Op0);
2787 if (cast<ConstantBool>(Cmp)->getValue()) {
2788 std::swap(LHS, RHS);
2789 std::swap(LHSCst, RHSCst);
2790 std::swap(LHSCC, RHSCC);
2791 }
2792
2793 // At this point, we know we have have two setcc instructions
2794 // comparing a value against two constants and or'ing the result
2795 // together. Because of the above check, we know that we only have
2796 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2797 // FoldSetCCLogical check above), that the two constants are not
2798 // equal.
2799 assert(LHSCst != RHSCst && "Compares not folded above?");
2800
2801 switch (LHSCC) {
2802 default: assert(0 && "Unknown integer condition code!");
2803 case Instruction::SetEQ:
2804 switch (RHSCC) {
2805 default: assert(0 && "Unknown integer condition code!");
2806 case Instruction::SetEQ:
2807 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2808 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2809 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2810 LHSVal->getName()+".off");
2811 InsertNewInstBefore(Add, I);
2812 const Type *UnsType = Add->getType()->getUnsignedVersion();
2813 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2814 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2815 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2816 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2817 }
2818 break; // (X == 13 | X == 15) -> no change
2819
Chris Lattner5c219462005-04-19 06:04:18 +00002820 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2821 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002822 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2823 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2824 return ReplaceInstUsesWith(I, RHS);
2825 }
2826 break;
2827 case Instruction::SetNE:
2828 switch (RHSCC) {
2829 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002830 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2831 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2832 return ReplaceInstUsesWith(I, LHS);
2833 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002834 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002835 return ReplaceInstUsesWith(I, ConstantBool::True);
2836 }
2837 break;
2838 case Instruction::SetLT:
2839 switch (RHSCC) {
2840 default: assert(0 && "Unknown integer condition code!");
2841 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2842 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002843 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2844 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002845 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2846 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2847 return ReplaceInstUsesWith(I, RHS);
2848 }
2849 break;
2850 case Instruction::SetGT:
2851 switch (RHSCC) {
2852 default: assert(0 && "Unknown integer condition code!");
2853 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2854 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2855 return ReplaceInstUsesWith(I, LHS);
2856 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2857 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2858 return ReplaceInstUsesWith(I, ConstantBool::True);
2859 }
2860 }
2861 }
2862 }
Chris Lattner15212982005-09-18 03:42:07 +00002863
Chris Lattner113f4f42002-06-25 16:13:24 +00002864 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002865}
2866
Chris Lattnerc2076352004-02-16 01:20:27 +00002867// XorSelf - Implements: X ^ X --> 0
2868struct XorSelf {
2869 Value *RHS;
2870 XorSelf(Value *rhs) : RHS(rhs) {}
2871 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2872 Instruction *apply(BinaryOperator &Xor) const {
2873 return &Xor;
2874 }
2875};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002876
2877
Chris Lattner113f4f42002-06-25 16:13:24 +00002878Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002879 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002881
Chris Lattner81a7a232004-10-16 18:11:37 +00002882 if (isa<UndefValue>(Op1))
2883 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2884
Chris Lattnerc2076352004-02-16 01:20:27 +00002885 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2886 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2887 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002888 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002889 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00002890
2891 // See if we can simplify any instructions used by the instruction whose sole
2892 // purpose is to compute bits we don't care about.
2893 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002894 if (!isa<PackedType>(I.getType()) &&
2895 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002896 KnownZero, KnownOne))
2897 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002898
Chris Lattner97638592003-07-23 21:37:07 +00002899 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00002900 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002901 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002902 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002903 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002904 return new SetCondInst(SCI->getInverseCondition(),
2905 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002906
Chris Lattner8f2f5982003-11-05 01:06:05 +00002907 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002908 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2909 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002910 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2911 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002912 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002913 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002914 }
Chris Lattner023a4832004-06-18 06:07:51 +00002915
2916 // ~(~X & Y) --> (X | ~Y)
2917 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2918 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2919 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2920 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002921 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002922 Op0I->getOperand(1)->getName()+".not");
2923 InsertNewInstBefore(NotY, I);
2924 return BinaryOperator::createOr(Op0NotVal, NotY);
2925 }
2926 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002927
Chris Lattner97638592003-07-23 21:37:07 +00002928 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00002929 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00002930 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002931 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002932 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2933 return BinaryOperator::createSub(
2934 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002935 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002936 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002937 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00002938 } else if (Op0I->getOpcode() == Instruction::Or) {
2939 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2940 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2941 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2942 // Anything in both C1 and C2 is known to be zero, remove it from
2943 // NewRHS.
2944 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2945 NewRHS = ConstantExpr::getAnd(NewRHS,
2946 ConstantExpr::getNot(CommonBits));
2947 WorkList.push_back(Op0I);
2948 I.setOperand(0, Op0I->getOperand(0));
2949 I.setOperand(1, NewRHS);
2950 return &I;
2951 }
Chris Lattner97638592003-07-23 21:37:07 +00002952 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002953 }
Chris Lattner183b3362004-04-09 19:05:30 +00002954
2955 // Try to fold constant and into select arguments.
2956 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002957 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002958 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002959 if (isa<PHINode>(Op0))
2960 if (Instruction *NV = FoldOpIntoPhi(I))
2961 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002962 }
2963
Chris Lattnerbb74e222003-03-10 23:06:50 +00002964 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002965 if (X == Op1)
2966 return ReplaceInstUsesWith(I,
2967 ConstantIntegral::getAllOnesValue(I.getType()));
2968
Chris Lattnerbb74e222003-03-10 23:06:50 +00002969 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002970 if (X == Op0)
2971 return ReplaceInstUsesWith(I,
2972 ConstantIntegral::getAllOnesValue(I.getType()));
2973
Chris Lattnerdcd07922006-04-01 08:03:55 +00002974 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002975 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002976 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00002977 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002978 I.swapOperands();
2979 std::swap(Op0, Op1);
2980 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00002981 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002982 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002983 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002984 } else if (Op1I->getOpcode() == Instruction::Xor) {
2985 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2986 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2987 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2988 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00002989 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
2990 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
2991 Op1I->swapOperands();
2992 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
2993 I.swapOperands(); // Simplified below.
2994 std::swap(Op0, Op1);
2995 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002996 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002997
Chris Lattnerdcd07922006-04-01 08:03:55 +00002998 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002999 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003000 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003001 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003002 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003003 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3004 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003005 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003006 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003007 } else if (Op0I->getOpcode() == Instruction::Xor) {
3008 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3009 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3010 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3011 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003012 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3013 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3014 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003015 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3016 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003017 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3018 InsertNewInstBefore(N, I);
3019 return BinaryOperator::createAnd(N, Op1);
3020 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003021 }
3022
Chris Lattner3ac7c262003-08-13 20:16:26 +00003023 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3024 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3025 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3026 return R;
3027
Chris Lattner113f4f42002-06-25 16:13:24 +00003028 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003029}
3030
Chris Lattner6862fbd2004-09-29 17:40:11 +00003031/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3032/// overflowed for this type.
3033static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3034 ConstantInt *In2) {
3035 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3036 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3037}
3038
3039static bool isPositive(ConstantInt *C) {
3040 return cast<ConstantSInt>(C)->getValue() >= 0;
3041}
3042
3043/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3044/// overflowed for this type.
3045static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3046 ConstantInt *In2) {
3047 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3048
3049 if (In1->getType()->isUnsigned())
3050 return cast<ConstantUInt>(Result)->getValue() <
3051 cast<ConstantUInt>(In1)->getValue();
3052 if (isPositive(In1) != isPositive(In2))
3053 return false;
3054 if (isPositive(In1))
3055 return cast<ConstantSInt>(Result)->getValue() <
3056 cast<ConstantSInt>(In1)->getValue();
3057 return cast<ConstantSInt>(Result)->getValue() >
3058 cast<ConstantSInt>(In1)->getValue();
3059}
3060
Chris Lattner0798af32005-01-13 20:14:25 +00003061/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3062/// code necessary to compute the offset from the base pointer (without adding
3063/// in the base pointer). Return the result as a signed integer of intptr size.
3064static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3065 TargetData &TD = IC.getTargetData();
3066 gep_type_iterator GTI = gep_type_begin(GEP);
3067 const Type *UIntPtrTy = TD.getIntPtrType();
3068 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3069 Value *Result = Constant::getNullValue(SIntPtrTy);
3070
3071 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003072 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003073
Chris Lattner0798af32005-01-13 20:14:25 +00003074 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3075 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003076 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003077 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3078 SIntPtrTy);
3079 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3080 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003081 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003082 Scale = ConstantExpr::getMul(OpC, Scale);
3083 if (Constant *RC = dyn_cast<Constant>(Result))
3084 Result = ConstantExpr::getAdd(RC, Scale);
3085 else {
3086 // Emit an add instruction.
3087 Result = IC.InsertNewInstBefore(
3088 BinaryOperator::createAdd(Result, Scale,
3089 GEP->getName()+".offs"), I);
3090 }
3091 }
3092 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003093 // Convert to correct type.
3094 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3095 Op->getName()+".c"), I);
3096 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003097 // We'll let instcombine(mul) convert this to a shl if possible.
3098 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3099 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003100
3101 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003102 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003103 GEP->getName()+".offs"), I);
3104 }
3105 }
3106 return Result;
3107}
3108
3109/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3110/// else. At this point we know that the GEP is on the LHS of the comparison.
3111Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3112 Instruction::BinaryOps Cond,
3113 Instruction &I) {
3114 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003115
3116 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3117 if (isa<PointerType>(CI->getOperand(0)->getType()))
3118 RHS = CI->getOperand(0);
3119
Chris Lattner0798af32005-01-13 20:14:25 +00003120 Value *PtrBase = GEPLHS->getOperand(0);
3121 if (PtrBase == RHS) {
3122 // As an optimization, we don't actually have to compute the actual value of
3123 // OFFSET if this is a seteq or setne comparison, just return whether each
3124 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003125 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3126 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003127 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3128 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003129 bool EmitIt = true;
3130 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3131 if (isa<UndefValue>(C)) // undef index -> undef.
3132 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3133 if (C->isNullValue())
3134 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003135 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3136 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003137 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003138 return ReplaceInstUsesWith(I, // No comparison is needed here.
3139 ConstantBool::get(Cond == Instruction::SetNE));
3140 }
3141
3142 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003143 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003144 new SetCondInst(Cond, GEPLHS->getOperand(i),
3145 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3146 if (InVal == 0)
3147 InVal = Comp;
3148 else {
3149 InVal = InsertNewInstBefore(InVal, I);
3150 InsertNewInstBefore(Comp, I);
3151 if (Cond == Instruction::SetNE) // True if any are unequal
3152 InVal = BinaryOperator::createOr(InVal, Comp);
3153 else // True if all are equal
3154 InVal = BinaryOperator::createAnd(InVal, Comp);
3155 }
3156 }
3157 }
3158
3159 if (InVal)
3160 return InVal;
3161 else
3162 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3163 ConstantBool::get(Cond == Instruction::SetEQ));
3164 }
Chris Lattner0798af32005-01-13 20:14:25 +00003165
3166 // Only lower this if the setcc is the only user of the GEP or if we expect
3167 // the result to fold to a constant!
3168 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3169 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3170 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3171 return new SetCondInst(Cond, Offset,
3172 Constant::getNullValue(Offset->getType()));
3173 }
3174 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003175 // If the base pointers are different, but the indices are the same, just
3176 // compare the base pointer.
3177 if (PtrBase != GEPRHS->getOperand(0)) {
3178 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003179 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003180 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003181 if (IndicesTheSame)
3182 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3183 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3184 IndicesTheSame = false;
3185 break;
3186 }
3187
3188 // If all indices are the same, just compare the base pointers.
3189 if (IndicesTheSame)
3190 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3191 GEPRHS->getOperand(0));
3192
3193 // Otherwise, the base pointers are different and the indices are
3194 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003195 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003196 }
Chris Lattner0798af32005-01-13 20:14:25 +00003197
Chris Lattner81e84172005-01-13 22:25:21 +00003198 // If one of the GEPs has all zero indices, recurse.
3199 bool AllZeros = true;
3200 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3201 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3202 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3203 AllZeros = false;
3204 break;
3205 }
3206 if (AllZeros)
3207 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3208 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003209
3210 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003211 AllZeros = true;
3212 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3213 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3214 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3215 AllZeros = false;
3216 break;
3217 }
3218 if (AllZeros)
3219 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3220
Chris Lattner4fa89822005-01-14 00:20:05 +00003221 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3222 // If the GEPs only differ by one index, compare it.
3223 unsigned NumDifferences = 0; // Keep track of # differences.
3224 unsigned DiffOperand = 0; // The operand that differs.
3225 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3226 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003227 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3228 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003229 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003230 NumDifferences = 2;
3231 break;
3232 } else {
3233 if (NumDifferences++) break;
3234 DiffOperand = i;
3235 }
3236 }
3237
3238 if (NumDifferences == 0) // SAME GEP?
3239 return ReplaceInstUsesWith(I, // No comparison is needed here.
3240 ConstantBool::get(Cond == Instruction::SetEQ));
3241 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003242 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3243 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003244
3245 // Convert the operands to signed values to make sure to perform a
3246 // signed comparison.
3247 const Type *NewTy = LHSV->getType()->getSignedVersion();
3248 if (LHSV->getType() != NewTy)
3249 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3250 LHSV->getName()), I);
3251 if (RHSV->getType() != NewTy)
3252 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3253 RHSV->getName()), I);
3254 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003255 }
3256 }
3257
Chris Lattner0798af32005-01-13 20:14:25 +00003258 // Only lower this if the setcc is the only user of the GEP or if we expect
3259 // the result to fold to a constant!
3260 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3261 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3262 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3263 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3264 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3265 return new SetCondInst(Cond, L, R);
3266 }
3267 }
3268 return 0;
3269}
3270
3271
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003272Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003273 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003274 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3275 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003276
3277 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003278 if (Op0 == Op1)
3279 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003280
Chris Lattner81a7a232004-10-16 18:11:37 +00003281 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3282 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3283
Chris Lattner15ff1e12004-11-14 07:33:16 +00003284 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3285 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003286 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3287 isa<ConstantPointerNull>(Op0)) &&
3288 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003289 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003290 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3291
3292 // setcc's with boolean values can always be turned into bitwise operations
3293 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003294 switch (I.getOpcode()) {
3295 default: assert(0 && "Invalid setcc instruction!");
3296 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003297 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003298 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003299 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003300 }
Chris Lattner4456da62004-08-11 00:50:51 +00003301 case Instruction::SetNE:
3302 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003303
Chris Lattner4456da62004-08-11 00:50:51 +00003304 case Instruction::SetGT:
3305 std::swap(Op0, Op1); // Change setgt -> setlt
3306 // FALL THROUGH
3307 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3308 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3309 InsertNewInstBefore(Not, I);
3310 return BinaryOperator::createAnd(Not, Op1);
3311 }
3312 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003313 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003314 // FALL THROUGH
3315 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3316 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3317 InsertNewInstBefore(Not, I);
3318 return BinaryOperator::createOr(Not, Op1);
3319 }
3320 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003321 }
3322
Chris Lattner2dd01742004-06-09 04:24:29 +00003323 // See if we are doing a comparison between a constant and an instruction that
3324 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003326 // Check to see if we are comparing against the minimum or maximum value...
3327 if (CI->isMinValue()) {
3328 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3329 return ReplaceInstUsesWith(I, ConstantBool::False);
3330 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3331 return ReplaceInstUsesWith(I, ConstantBool::True);
3332 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3333 return BinaryOperator::createSetEQ(Op0, Op1);
3334 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3335 return BinaryOperator::createSetNE(Op0, Op1);
3336
3337 } else if (CI->isMaxValue()) {
3338 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3339 return ReplaceInstUsesWith(I, ConstantBool::False);
3340 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3341 return ReplaceInstUsesWith(I, ConstantBool::True);
3342 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3343 return BinaryOperator::createSetEQ(Op0, Op1);
3344 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3345 return BinaryOperator::createSetNE(Op0, Op1);
3346
3347 // Comparing against a value really close to min or max?
3348 } else if (isMinValuePlusOne(CI)) {
3349 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3350 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3351 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3352 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3353
3354 } else if (isMaxValueMinusOne(CI)) {
3355 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3356 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3357 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3358 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3359 }
3360
3361 // If we still have a setle or setge instruction, turn it into the
3362 // appropriate setlt or setgt instruction. Since the border cases have
3363 // already been handled above, this requires little checking.
3364 //
3365 if (I.getOpcode() == Instruction::SetLE)
3366 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3367 if (I.getOpcode() == Instruction::SetGE)
3368 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3369
Chris Lattneree0f2802006-02-12 02:07:56 +00003370
3371 // See if we can fold the comparison based on bits known to be zero or one
3372 // in the input.
3373 uint64_t KnownZero, KnownOne;
3374 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3375 KnownZero, KnownOne, 0))
3376 return &I;
3377
3378 // Given the known and unknown bits, compute a range that the LHS could be
3379 // in.
3380 if (KnownOne | KnownZero) {
3381 if (Ty->isUnsigned()) { // Unsigned comparison.
3382 uint64_t Min, Max;
3383 uint64_t RHSVal = CI->getZExtValue();
3384 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3385 Min, Max);
3386 switch (I.getOpcode()) { // LE/GE have been folded already.
3387 default: assert(0 && "Unknown setcc opcode!");
3388 case Instruction::SetEQ:
3389 if (Max < RHSVal || Min > RHSVal)
3390 return ReplaceInstUsesWith(I, ConstantBool::False);
3391 break;
3392 case Instruction::SetNE:
3393 if (Max < RHSVal || Min > RHSVal)
3394 return ReplaceInstUsesWith(I, ConstantBool::True);
3395 break;
3396 case Instruction::SetLT:
3397 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3398 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3399 break;
3400 case Instruction::SetGT:
3401 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3402 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3403 break;
3404 }
3405 } else { // Signed comparison.
3406 int64_t Min, Max;
3407 int64_t RHSVal = CI->getSExtValue();
3408 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3409 Min, Max);
3410 switch (I.getOpcode()) { // LE/GE have been folded already.
3411 default: assert(0 && "Unknown setcc opcode!");
3412 case Instruction::SetEQ:
3413 if (Max < RHSVal || Min > RHSVal)
3414 return ReplaceInstUsesWith(I, ConstantBool::False);
3415 break;
3416 case Instruction::SetNE:
3417 if (Max < RHSVal || Min > RHSVal)
3418 return ReplaceInstUsesWith(I, ConstantBool::True);
3419 break;
3420 case Instruction::SetLT:
3421 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3422 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3423 break;
3424 case Instruction::SetGT:
3425 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3426 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3427 break;
3428 }
3429 }
3430 }
3431
3432
Chris Lattnere1e10e12004-05-25 06:32:08 +00003433 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003434 switch (LHSI->getOpcode()) {
3435 case Instruction::And:
3436 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3437 LHSI->getOperand(0)->hasOneUse()) {
3438 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3439 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3440 // happens a LOT in code produced by the C front-end, for bitfield
3441 // access.
3442 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003443 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3444
3445 // Check to see if there is a noop-cast between the shift and the and.
3446 if (!Shift) {
3447 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3448 if (CI->getOperand(0)->getType()->isIntegral() &&
3449 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3450 CI->getType()->getPrimitiveSizeInBits())
3451 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3452 }
3453
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003454 ConstantUInt *ShAmt;
3455 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003456 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3457 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003458
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003459 // We can fold this as long as we can't shift unknown bits
3460 // into the mask. This can only happen with signed shift
3461 // rights, as they sign-extend.
3462 if (ShAmt) {
3463 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003464 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003465 if (!CanFold) {
3466 // To test for the bad case of the signed shr, see if any
3467 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003468 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3469 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3470
3471 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003472 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003473 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3474 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003475 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3476 CanFold = true;
3477 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003478
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003479 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003480 Constant *NewCst;
3481 if (Shift->getOpcode() == Instruction::Shl)
3482 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3483 else
3484 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003485
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003486 // Check to see if we are shifting out any of the bits being
3487 // compared.
3488 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3489 // If we shifted bits out, the fold is not going to work out.
3490 // As a special case, check to see if this means that the
3491 // result is always true or false now.
3492 if (I.getOpcode() == Instruction::SetEQ)
3493 return ReplaceInstUsesWith(I, ConstantBool::False);
3494 if (I.getOpcode() == Instruction::SetNE)
3495 return ReplaceInstUsesWith(I, ConstantBool::True);
3496 } else {
3497 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003498 Constant *NewAndCST;
3499 if (Shift->getOpcode() == Instruction::Shl)
3500 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3501 else
3502 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3503 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003504 if (AndTy == Ty)
3505 LHSI->setOperand(0, Shift->getOperand(0));
3506 else {
3507 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3508 *Shift);
3509 LHSI->setOperand(0, NewCast);
3510 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003511 WorkList.push_back(Shift); // Shift is dead.
3512 AddUsesToWorkList(I);
3513 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003514 }
3515 }
Chris Lattner35167c32004-06-09 07:59:58 +00003516 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003517 }
3518 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003519
Chris Lattner272d5ca2004-09-28 18:22:15 +00003520 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3521 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3522 switch (I.getOpcode()) {
3523 default: break;
3524 case Instruction::SetEQ:
3525 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003526 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3527
3528 // Check that the shift amount is in range. If not, don't perform
3529 // undefined shifts. When the shift is visited it will be
3530 // simplified.
3531 if (ShAmt->getValue() >= TypeBits)
3532 break;
3533
Chris Lattner272d5ca2004-09-28 18:22:15 +00003534 // If we are comparing against bits always shifted out, the
3535 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003536 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003537 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3538 if (Comp != CI) {// Comparing against a bit that we know is zero.
3539 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3540 Constant *Cst = ConstantBool::get(IsSetNE);
3541 return ReplaceInstUsesWith(I, Cst);
3542 }
3543
3544 if (LHSI->hasOneUse()) {
3545 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003546 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003547 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3548
3549 Constant *Mask;
3550 if (CI->getType()->isUnsigned()) {
3551 Mask = ConstantUInt::get(CI->getType(), Val);
3552 } else if (ShAmtVal != 0) {
3553 Mask = ConstantSInt::get(CI->getType(), Val);
3554 } else {
3555 Mask = ConstantInt::getAllOnesValue(CI->getType());
3556 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003557
Chris Lattner272d5ca2004-09-28 18:22:15 +00003558 Instruction *AndI =
3559 BinaryOperator::createAnd(LHSI->getOperand(0),
3560 Mask, LHSI->getName()+".mask");
3561 Value *And = InsertNewInstBefore(AndI, I);
3562 return new SetCondInst(I.getOpcode(), And,
3563 ConstantExpr::getUShr(CI, ShAmt));
3564 }
3565 }
3566 }
3567 }
3568 break;
3569
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003570 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003571 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003572 switch (I.getOpcode()) {
3573 default: break;
3574 case Instruction::SetEQ:
3575 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003576
3577 // Check that the shift amount is in range. If not, don't perform
3578 // undefined shifts. When the shift is visited it will be
3579 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003580 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003581 if (ShAmt->getValue() >= TypeBits)
3582 break;
3583
Chris Lattner1023b872004-09-27 16:18:50 +00003584 // If we are comparing against bits always shifted out, the
3585 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003586 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003587 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003588
Chris Lattner1023b872004-09-27 16:18:50 +00003589 if (Comp != CI) {// Comparing against a bit that we know is zero.
3590 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3591 Constant *Cst = ConstantBool::get(IsSetNE);
3592 return ReplaceInstUsesWith(I, Cst);
3593 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003594
Chris Lattner1023b872004-09-27 16:18:50 +00003595 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003596 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003597
Chris Lattner1023b872004-09-27 16:18:50 +00003598 // Otherwise strength reduce the shift into an and.
3599 uint64_t Val = ~0ULL; // All ones.
3600 Val <<= ShAmtVal; // Shift over to the right spot.
3601
3602 Constant *Mask;
3603 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003604 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003605 Mask = ConstantUInt::get(CI->getType(), Val);
3606 } else {
3607 Mask = ConstantSInt::get(CI->getType(), Val);
3608 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003609
Chris Lattner1023b872004-09-27 16:18:50 +00003610 Instruction *AndI =
3611 BinaryOperator::createAnd(LHSI->getOperand(0),
3612 Mask, LHSI->getName()+".mask");
3613 Value *And = InsertNewInstBefore(AndI, I);
3614 return new SetCondInst(I.getOpcode(), And,
3615 ConstantExpr::getShl(CI, ShAmt));
3616 }
3617 break;
3618 }
3619 }
3620 }
3621 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003622
Chris Lattner6862fbd2004-09-29 17:40:11 +00003623 case Instruction::Div:
3624 // Fold: (div X, C1) op C2 -> range check
3625 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3626 // Fold this div into the comparison, producing a range check.
3627 // Determine, based on the divide type, what the range is being
3628 // checked. If there is an overflow on the low or high side, remember
3629 // it, otherwise compute the range [low, hi) bounding the new value.
3630 bool LoOverflow = false, HiOverflow = 0;
3631 ConstantInt *LoBound = 0, *HiBound = 0;
3632
3633 ConstantInt *Prod;
3634 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3635
Chris Lattnera92af962004-10-11 19:40:04 +00003636 Instruction::BinaryOps Opcode = I.getOpcode();
3637
Chris Lattner6862fbd2004-09-29 17:40:11 +00003638 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3639 } else if (LHSI->getType()->isUnsigned()) { // udiv
3640 LoBound = Prod;
3641 LoOverflow = ProdOV;
3642 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3643 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3644 if (CI->isNullValue()) { // (X / pos) op 0
3645 // Can't overflow.
3646 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3647 HiBound = DivRHS;
3648 } else if (isPositive(CI)) { // (X / pos) op pos
3649 LoBound = Prod;
3650 LoOverflow = ProdOV;
3651 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3652 } else { // (X / pos) op neg
3653 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3654 LoOverflow = AddWithOverflow(LoBound, Prod,
3655 cast<ConstantInt>(DivRHSH));
3656 HiBound = Prod;
3657 HiOverflow = ProdOV;
3658 }
3659 } else { // Divisor is < 0.
3660 if (CI->isNullValue()) { // (X / neg) op 0
3661 LoBound = AddOne(DivRHS);
3662 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003663 if (HiBound == DivRHS)
3664 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003665 } else if (isPositive(CI)) { // (X / neg) op pos
3666 HiOverflow = LoOverflow = ProdOV;
3667 if (!LoOverflow)
3668 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3669 HiBound = AddOne(Prod);
3670 } else { // (X / neg) op neg
3671 LoBound = Prod;
3672 LoOverflow = HiOverflow = ProdOV;
3673 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3674 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003675
Chris Lattnera92af962004-10-11 19:40:04 +00003676 // Dividing by a negate swaps the condition.
3677 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003678 }
3679
3680 if (LoBound) {
3681 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003682 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003683 default: assert(0 && "Unhandled setcc opcode!");
3684 case Instruction::SetEQ:
3685 if (LoOverflow && HiOverflow)
3686 return ReplaceInstUsesWith(I, ConstantBool::False);
3687 else if (HiOverflow)
3688 return new SetCondInst(Instruction::SetGE, X, LoBound);
3689 else if (LoOverflow)
3690 return new SetCondInst(Instruction::SetLT, X, HiBound);
3691 else
3692 return InsertRangeTest(X, LoBound, HiBound, true, I);
3693 case Instruction::SetNE:
3694 if (LoOverflow && HiOverflow)
3695 return ReplaceInstUsesWith(I, ConstantBool::True);
3696 else if (HiOverflow)
3697 return new SetCondInst(Instruction::SetLT, X, LoBound);
3698 else if (LoOverflow)
3699 return new SetCondInst(Instruction::SetGE, X, HiBound);
3700 else
3701 return InsertRangeTest(X, LoBound, HiBound, false, I);
3702 case Instruction::SetLT:
3703 if (LoOverflow)
3704 return ReplaceInstUsesWith(I, ConstantBool::False);
3705 return new SetCondInst(Instruction::SetLT, X, LoBound);
3706 case Instruction::SetGT:
3707 if (HiOverflow)
3708 return ReplaceInstUsesWith(I, ConstantBool::False);
3709 return new SetCondInst(Instruction::SetGE, X, HiBound);
3710 }
3711 }
3712 }
3713 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003714 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003715
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003716 // Simplify seteq and setne instructions...
3717 if (I.getOpcode() == Instruction::SetEQ ||
3718 I.getOpcode() == Instruction::SetNE) {
3719 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3720
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003721 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003722 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003723 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3724 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003725 case Instruction::Rem:
3726 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3727 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3728 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003729 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3730 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3731 if (isPowerOf2_64(V)) {
3732 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003733 const Type *UTy = BO->getType()->getUnsignedVersion();
3734 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3735 UTy, "tmp"), I);
3736 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3737 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3738 RHSCst, BO->getName()), I);
3739 return BinaryOperator::create(I.getOpcode(), NewRem,
3740 Constant::getNullValue(UTy));
3741 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003742 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003743 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003744
Chris Lattnerc992add2003-08-13 05:33:12 +00003745 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003746 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3747 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003748 if (BO->hasOneUse())
3749 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3750 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003751 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003752 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3753 // efficiently invertible, or if the add has just this one use.
3754 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003755
Chris Lattnerc992add2003-08-13 05:33:12 +00003756 if (Value *NegVal = dyn_castNegVal(BOp1))
3757 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3758 else if (Value *NegVal = dyn_castNegVal(BOp0))
3759 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003760 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003761 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3762 BO->setName("");
3763 InsertNewInstBefore(Neg, I);
3764 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3765 }
3766 }
3767 break;
3768 case Instruction::Xor:
3769 // For the xor case, we can xor two constants together, eliminating
3770 // the explicit xor.
3771 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3772 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003773 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003774
3775 // FALLTHROUGH
3776 case Instruction::Sub:
3777 // Replace (([sub|xor] A, B) != 0) with (A != B)
3778 if (CI->isNullValue())
3779 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3780 BO->getOperand(1));
3781 break;
3782
3783 case Instruction::Or:
3784 // If bits are being or'd in that are not present in the constant we
3785 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003786 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003787 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003788 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003789 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003790 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003791 break;
3792
3793 case Instruction::And:
3794 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003795 // If bits are being compared against that are and'd out, then the
3796 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003797 if (!ConstantExpr::getAnd(CI,
3798 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003799 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003800
Chris Lattner35167c32004-06-09 07:59:58 +00003801 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003802 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003803 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3804 Instruction::SetNE, Op0,
3805 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003806
Chris Lattnerc992add2003-08-13 05:33:12 +00003807 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3808 // to be a signed value as appropriate.
3809 if (isSignBit(BOC)) {
3810 Value *X = BO->getOperand(0);
3811 // If 'X' is not signed, insert a cast now...
3812 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003813 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003814 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003815 }
3816 return new SetCondInst(isSetNE ? Instruction::SetLT :
3817 Instruction::SetGE, X,
3818 Constant::getNullValue(X->getType()));
3819 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003820
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003821 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003822 if (CI->isNullValue() && isHighOnes(BOC)) {
3823 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003824 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003825
3826 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003827 if (NegX->getType()->isSigned()) {
3828 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3829 X = InsertCastBefore(X, DestTy, I);
3830 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003831 }
3832
3833 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003834 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003835 }
3836
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003837 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003838 default: break;
3839 }
3840 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003841 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003842 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003843 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3844 Value *CastOp = Cast->getOperand(0);
3845 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003846 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003847 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003848 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003849 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003850 "Source and destination signednesses should differ!");
3851 if (Cast->getType()->isSigned()) {
3852 // If this is a signed comparison, check for comparisons in the
3853 // vicinity of zero.
3854 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3855 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003856 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003857 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003858 else if (I.getOpcode() == Instruction::SetGT &&
3859 cast<ConstantSInt>(CI)->getValue() == -1)
3860 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003861 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003862 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003863 } else {
3864 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3865 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003866 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003867 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003868 return BinaryOperator::createSetGT(CastOp,
3869 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003870 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003871 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003872 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003873 return BinaryOperator::createSetLT(CastOp,
3874 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003875 }
3876 }
3877 }
Chris Lattnere967b342003-06-04 05:10:11 +00003878 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003879 }
3880
Chris Lattner77c32c32005-04-23 15:31:55 +00003881 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3882 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3883 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3884 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003885 case Instruction::GetElementPtr:
3886 if (RHSC->isNullValue()) {
3887 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3888 bool isAllZeros = true;
3889 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3890 if (!isa<Constant>(LHSI->getOperand(i)) ||
3891 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3892 isAllZeros = false;
3893 break;
3894 }
3895 if (isAllZeros)
3896 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3897 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3898 }
3899 break;
3900
Chris Lattner77c32c32005-04-23 15:31:55 +00003901 case Instruction::PHI:
3902 if (Instruction *NV = FoldOpIntoPhi(I))
3903 return NV;
3904 break;
3905 case Instruction::Select:
3906 // If either operand of the select is a constant, we can fold the
3907 // comparison into the select arms, which will cause one to be
3908 // constant folded and the select turned into a bitwise or.
3909 Value *Op1 = 0, *Op2 = 0;
3910 if (LHSI->hasOneUse()) {
3911 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3912 // Fold the known value into the constant operand.
3913 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3914 // Insert a new SetCC of the other select operand.
3915 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3916 LHSI->getOperand(2), RHSC,
3917 I.getName()), I);
3918 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3919 // Fold the known value into the constant operand.
3920 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3921 // Insert a new SetCC of the other select operand.
3922 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3923 LHSI->getOperand(1), RHSC,
3924 I.getName()), I);
3925 }
3926 }
Jeff Cohen82639852005-04-23 21:38:35 +00003927
Chris Lattner77c32c32005-04-23 15:31:55 +00003928 if (Op1)
3929 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3930 break;
3931 }
3932 }
3933
Chris Lattner0798af32005-01-13 20:14:25 +00003934 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3935 if (User *GEP = dyn_castGetElementPtr(Op0))
3936 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3937 return NI;
3938 if (User *GEP = dyn_castGetElementPtr(Op1))
3939 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3940 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3941 return NI;
3942
Chris Lattner16930792003-11-03 04:25:02 +00003943 // Test to see if the operands of the setcc are casted versions of other
3944 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003945 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3946 Value *CastOp0 = CI->getOperand(0);
3947 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003948 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003949 (I.getOpcode() == Instruction::SetEQ ||
3950 I.getOpcode() == Instruction::SetNE)) {
3951 // We keep moving the cast from the left operand over to the right
3952 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003953 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003954
Chris Lattner16930792003-11-03 04:25:02 +00003955 // If operand #1 is a cast instruction, see if we can eliminate it as
3956 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003957 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3958 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003959 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003960 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003961
Chris Lattner16930792003-11-03 04:25:02 +00003962 // If Op1 is a constant, we can fold the cast into the constant.
3963 if (Op1->getType() != Op0->getType())
3964 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3965 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3966 } else {
3967 // Otherwise, cast the RHS right before the setcc
3968 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3969 InsertNewInstBefore(cast<Instruction>(Op1), I);
3970 }
3971 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3972 }
3973
Chris Lattner6444c372003-11-03 05:17:03 +00003974 // Handle the special case of: setcc (cast bool to X), <cst>
3975 // This comes up when you have code like
3976 // int X = A < B;
3977 // if (X) ...
3978 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003979 // with a constant or another cast from the same type.
3980 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3981 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3982 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003983 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00003984
3985 if (I.getOpcode() == Instruction::SetNE ||
3986 I.getOpcode() == Instruction::SetEQ) {
3987 Value *A, *B;
3988 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3989 (A == Op1 || B == Op1)) {
3990 // (A^B) == A -> B == 0
3991 Value *OtherVal = A == Op1 ? B : A;
3992 return BinaryOperator::create(I.getOpcode(), OtherVal,
3993 Constant::getNullValue(A->getType()));
3994 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3995 (A == Op0 || B == Op0)) {
3996 // A == (A^B) -> B == 0
3997 Value *OtherVal = A == Op0 ? B : A;
3998 return BinaryOperator::create(I.getOpcode(), OtherVal,
3999 Constant::getNullValue(A->getType()));
4000 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4001 // (A-B) == A -> B == 0
4002 return BinaryOperator::create(I.getOpcode(), B,
4003 Constant::getNullValue(B->getType()));
4004 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4005 // A == (A-B) -> B == 0
4006 return BinaryOperator::create(I.getOpcode(), B,
4007 Constant::getNullValue(B->getType()));
4008 }
4009 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004010 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004011}
4012
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004013// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4014// We only handle extending casts so far.
4015//
4016Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4017 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4018 const Type *SrcTy = LHSCIOp->getType();
4019 const Type *DestTy = SCI.getOperand(0)->getType();
4020 Value *RHSCIOp;
4021
4022 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004023 return 0;
4024
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004025 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4026 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4027 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4028
4029 // Is this a sign or zero extension?
4030 bool isSignSrc = SrcTy->isSigned();
4031 bool isSignDest = DestTy->isSigned();
4032
4033 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4034 // Not an extension from the same type?
4035 RHSCIOp = CI->getOperand(0);
4036 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4037 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4038 // Compute the constant that would happen if we truncated to SrcTy then
4039 // reextended to DestTy.
4040 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4041
4042 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4043 RHSCIOp = Res;
4044 } else {
4045 // If the value cannot be represented in the shorter type, we cannot emit
4046 // a simple comparison.
4047 if (SCI.getOpcode() == Instruction::SetEQ)
4048 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4049 if (SCI.getOpcode() == Instruction::SetNE)
4050 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4051
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004052 // Evaluate the comparison for LT.
4053 Value *Result;
4054 if (DestTy->isSigned()) {
4055 // We're performing a signed comparison.
4056 if (isSignSrc) {
4057 // Signed extend and signed comparison.
4058 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4059 Result = ConstantBool::False;
4060 else
4061 Result = ConstantBool::True; // X < (large) --> true
4062 } else {
4063 // Unsigned extend and signed comparison.
4064 if (cast<ConstantSInt>(CI)->getValue() < 0)
4065 Result = ConstantBool::False;
4066 else
4067 Result = ConstantBool::True;
4068 }
4069 } else {
4070 // We're performing an unsigned comparison.
4071 if (!isSignSrc) {
4072 // Unsigned extend & compare -> always true.
4073 Result = ConstantBool::True;
4074 } else {
4075 // We're performing an unsigned comp with a sign extended value.
4076 // This is true if the input is >= 0. [aka >s -1]
4077 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4078 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4079 NegOne, SCI.getName()), SCI);
4080 }
Reid Spencer279fa252004-11-28 21:31:15 +00004081 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004082
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004083 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004084 if (SCI.getOpcode() == Instruction::SetLT) {
4085 return ReplaceInstUsesWith(SCI, Result);
4086 } else {
4087 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4088 if (Constant *CI = dyn_cast<Constant>(Result))
4089 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4090 else
4091 return BinaryOperator::createNot(Result);
4092 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004093 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004094 } else {
4095 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004096 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004097
Chris Lattner252a8452005-06-16 03:00:08 +00004098 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004099 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4100}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004101
Chris Lattnere8d6c602003-03-10 19:16:08 +00004102Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004103 assert(I.getOperand(1)->getType() == Type::UByteTy);
4104 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004105 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004106
4107 // shl X, 0 == X and shr X, 0 == X
4108 // shl 0, X == 0 and shr 0, X == 0
4109 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004110 Op0 == Constant::getNullValue(Op0->getType()))
4111 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004112
Chris Lattner81a7a232004-10-16 18:11:37 +00004113 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4114 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004115 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004116 else // undef << X -> 0 AND undef >>u X -> 0
4117 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4118 }
4119 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004120 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004121 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4122 else
4123 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4124 }
4125
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004126 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4127 if (!isLeftShift)
4128 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4129 if (CSI->isAllOnesValue())
4130 return ReplaceInstUsesWith(I, CSI);
4131
Chris Lattner183b3362004-04-09 19:05:30 +00004132 // Try to fold constant and into select arguments.
4133 if (isa<Constant>(Op0))
4134 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004135 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004136 return R;
4137
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004138 // See if we can turn a signed shr into an unsigned shr.
4139 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004140 if (MaskedValueIsZero(Op0,
4141 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004142 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4143 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4144 I.getName()), I);
4145 return new CastInst(V, I.getType());
4146 }
4147 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004148
Chris Lattner14553932006-01-06 07:12:35 +00004149 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4150 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4151 return Res;
4152 return 0;
4153}
4154
4155Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4156 ShiftInst &I) {
4157 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004158 bool isSignedShift = Op0->getType()->isSigned();
4159 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004160
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004161 // See if we can simplify any instructions used by the instruction whose sole
4162 // purpose is to compute bits we don't care about.
4163 uint64_t KnownZero, KnownOne;
4164 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4165 KnownZero, KnownOne))
4166 return &I;
4167
Chris Lattner14553932006-01-06 07:12:35 +00004168 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4169 // of a signed value.
4170 //
4171 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4172 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004173 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004174 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4175 else {
4176 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4177 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004178 }
Chris Lattner14553932006-01-06 07:12:35 +00004179 }
4180
4181 // ((X*C1) << C2) == (X * (C1 << C2))
4182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4183 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4184 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4185 return BinaryOperator::createMul(BO->getOperand(0),
4186 ConstantExpr::getShl(BOOp, Op1));
4187
4188 // Try to fold constant and into select arguments.
4189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4190 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4191 return R;
4192 if (isa<PHINode>(Op0))
4193 if (Instruction *NV = FoldOpIntoPhi(I))
4194 return NV;
4195
4196 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004197 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4198 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4199 Value *V1, *V2;
4200 ConstantInt *CC;
4201 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004202 default: break;
4203 case Instruction::Add:
4204 case Instruction::And:
4205 case Instruction::Or:
4206 case Instruction::Xor:
4207 // These operators commute.
4208 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004209 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4210 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004211 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004212 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004213 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004214 Op0BO->getName());
4215 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004216 Instruction *X =
4217 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4218 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004219 InsertNewInstBefore(X, I); // (X + (Y << C))
4220 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004221 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004222 return BinaryOperator::createAnd(X, C2);
4223 }
Chris Lattner14553932006-01-06 07:12:35 +00004224
Chris Lattner797dee72005-09-18 06:30:59 +00004225 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4226 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4227 match(Op0BO->getOperand(1),
4228 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004229 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004230 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004231 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004232 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004233 Op0BO->getName());
4234 InsertNewInstBefore(YS, I); // (Y << C)
4235 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004236 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004237 V1->getName()+".mask");
4238 InsertNewInstBefore(XM, I); // X & (CC << C)
4239
4240 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4241 }
Chris Lattner14553932006-01-06 07:12:35 +00004242
Chris Lattner797dee72005-09-18 06:30:59 +00004243 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004244 case Instruction::Sub:
4245 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004246 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4247 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004248 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004249 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004250 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004251 Op0BO->getName());
4252 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004253 Instruction *X =
4254 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4255 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004256 InsertNewInstBefore(X, I); // (X + (Y << C))
4257 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004258 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004259 return BinaryOperator::createAnd(X, C2);
4260 }
Chris Lattner14553932006-01-06 07:12:35 +00004261
Chris Lattner797dee72005-09-18 06:30:59 +00004262 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4263 match(Op0BO->getOperand(0),
4264 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004265 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004266 cast<BinaryOperator>(Op0BO->getOperand(0))
4267 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004268 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004269 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004270 Op0BO->getName());
4271 InsertNewInstBefore(YS, I); // (Y << C)
4272 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004273 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004274 V1->getName()+".mask");
4275 InsertNewInstBefore(XM, I); // X & (CC << C)
4276
4277 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4278 }
Chris Lattner14553932006-01-06 07:12:35 +00004279
Chris Lattner27cb9db2005-09-18 05:12:10 +00004280 break;
Chris Lattner14553932006-01-06 07:12:35 +00004281 }
4282
4283
4284 // If the operand is an bitwise operator with a constant RHS, and the
4285 // shift is the only use, we can pull it out of the shift.
4286 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4287 bool isValid = true; // Valid only for And, Or, Xor
4288 bool highBitSet = false; // Transform if high bit of constant set?
4289
4290 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004291 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004292 case Instruction::Add:
4293 isValid = isLeftShift;
4294 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004295 case Instruction::Or:
4296 case Instruction::Xor:
4297 highBitSet = false;
4298 break;
4299 case Instruction::And:
4300 highBitSet = true;
4301 break;
Chris Lattner14553932006-01-06 07:12:35 +00004302 }
4303
4304 // If this is a signed shift right, and the high bit is modified
4305 // by the logical operation, do not perform the transformation.
4306 // The highBitSet boolean indicates the value of the high bit of
4307 // the constant which would cause it to be modified for this
4308 // operation.
4309 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004310 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004311 uint64_t Val = Op0C->getRawValue();
4312 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4313 }
4314
4315 if (isValid) {
4316 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4317
4318 Instruction *NewShift =
4319 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4320 Op0BO->getName());
4321 Op0BO->setName("");
4322 InsertNewInstBefore(NewShift, I);
4323
4324 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4325 NewRHS);
4326 }
4327 }
4328 }
4329 }
4330
Chris Lattnereb372a02006-01-06 07:52:12 +00004331 // Find out if this is a shift of a shift by a constant.
4332 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004333 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004334 ShiftOp = Op0SI;
4335 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4336 // If this is a noop-integer case of a shift instruction, use the shift.
4337 if (CI->getOperand(0)->getType()->isInteger() &&
4338 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4339 CI->getType()->getPrimitiveSizeInBits() &&
4340 isa<ShiftInst>(CI->getOperand(0))) {
4341 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4342 }
4343 }
4344
4345 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4346 // Find the operands and properties of the input shift. Note that the
4347 // signedness of the input shift may differ from the current shift if there
4348 // is a noop cast between the two.
4349 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4350 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004351 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004352
4353 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4354
4355 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4356 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4357
4358 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4359 if (isLeftShift == isShiftOfLeftShift) {
4360 // Do not fold these shifts if the first one is signed and the second one
4361 // is unsigned and this is a right shift. Further, don't do any folding
4362 // on them.
4363 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4364 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004365
Chris Lattnereb372a02006-01-06 07:52:12 +00004366 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4367 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4368 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004369
Chris Lattnereb372a02006-01-06 07:52:12 +00004370 Value *Op = ShiftOp->getOperand(0);
4371 if (isShiftOfSignedShift != isSignedShift)
4372 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4373 return new ShiftInst(I.getOpcode(), Op,
4374 ConstantUInt::get(Type::UByteTy, Amt));
4375 }
4376
4377 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4378 // signed types, we can only support the (A >> c1) << c2 configuration,
4379 // because it can not turn an arbitrary bit of A into a sign bit.
4380 if (isUnsignedShift || isLeftShift) {
4381 // Calculate bitmask for what gets shifted off the edge.
4382 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4383 if (isLeftShift)
4384 C = ConstantExpr::getShl(C, ShiftAmt1C);
4385 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004386 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004387
4388 Value *Op = ShiftOp->getOperand(0);
4389 if (isShiftOfSignedShift != isSignedShift)
4390 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4391
4392 Instruction *Mask =
4393 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4394 InsertNewInstBefore(Mask, I);
4395
4396 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004397 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004398 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004399 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004400 return new ShiftInst(I.getOpcode(), Mask,
4401 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004402 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4403 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4404 // Make sure to emit an unsigned shift right, not a signed one.
4405 Mask = InsertNewInstBefore(new CastInst(Mask,
4406 Mask->getType()->getUnsignedVersion(),
4407 Op->getName()), I);
4408 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004409 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004410 InsertNewInstBefore(Mask, I);
4411 return new CastInst(Mask, I.getType());
4412 } else {
4413 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4414 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4415 }
4416 } else {
4417 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4418 Op = InsertNewInstBefore(new CastInst(Mask,
4419 I.getType()->getSignedVersion(),
4420 Mask->getName()), I);
4421 Instruction *Shift =
4422 new ShiftInst(ShiftOp->getOpcode(), Op,
4423 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4424 InsertNewInstBefore(Shift, I);
4425
4426 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4427 C = ConstantExpr::getShl(C, Op1);
4428 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4429 InsertNewInstBefore(Mask, I);
4430 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004431 }
4432 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004433 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004434 // this case, C1 == C2 and C1 is 8, 16, or 32.
4435 if (ShiftAmt1 == ShiftAmt2) {
4436 const Type *SExtType = 0;
4437 switch (ShiftAmt1) {
4438 case 8 : SExtType = Type::SByteTy; break;
4439 case 16: SExtType = Type::ShortTy; break;
4440 case 32: SExtType = Type::IntTy; break;
4441 }
4442
4443 if (SExtType) {
4444 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4445 SExtType, "sext");
4446 InsertNewInstBefore(NewTrunc, I);
4447 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004448 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004449 }
Chris Lattner86102b82005-01-01 16:22:27 +00004450 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004451 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004452 return 0;
4453}
4454
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004455enum CastType {
4456 Noop = 0,
4457 Truncate = 1,
4458 Signext = 2,
4459 Zeroext = 3
4460};
4461
4462/// getCastType - In the future, we will split the cast instruction into these
4463/// various types. Until then, we have to do the analysis here.
4464static CastType getCastType(const Type *Src, const Type *Dest) {
4465 assert(Src->isIntegral() && Dest->isIntegral() &&
4466 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004467 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4468 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004469
4470 if (SrcSize == DestSize) return Noop;
4471 if (SrcSize > DestSize) return Truncate;
4472 if (Src->isSigned()) return Signext;
4473 return Zeroext;
4474}
4475
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004476
Chris Lattner48a44f72002-05-02 17:06:02 +00004477// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4478// instruction.
4479//
Chris Lattnere154abf2006-01-19 07:40:22 +00004480static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4481 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004482
Chris Lattner650b6da2002-08-02 20:00:25 +00004483 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004484 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004485 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004486 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004487 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004488
Chris Lattner4fbad962004-07-21 04:27:24 +00004489 // If we are casting between pointer and integer types, treat pointers as
4490 // integers of the appropriate size for the code below.
4491 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4492 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4493 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004494
Chris Lattner48a44f72002-05-02 17:06:02 +00004495 // Allow free casting and conversion of sizes as long as the sign doesn't
4496 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004497 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004498 CastType FirstCast = getCastType(SrcTy, MidTy);
4499 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004500
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004501 // Capture the effect of these two casts. If the result is a legal cast,
4502 // the CastType is stored here, otherwise a special code is used.
4503 static const unsigned CastResult[] = {
4504 // First cast is noop
4505 0, 1, 2, 3,
4506 // First cast is a truncate
4507 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4508 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004509 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004510 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004511 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004512 };
4513
4514 unsigned Result = CastResult[FirstCast*4+SecondCast];
4515 switch (Result) {
4516 default: assert(0 && "Illegal table value!");
4517 case 0:
4518 case 1:
4519 case 2:
4520 case 3:
4521 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4522 // truncates, we could eliminate more casts.
4523 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4524 case 4:
4525 return false; // Not possible to eliminate this here.
4526 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004527 // Sign or zero extend followed by truncate is always ok if the result
4528 // is a truncate or noop.
4529 CastType ResultCast = getCastType(SrcTy, DstTy);
4530 if (ResultCast == Noop || ResultCast == Truncate)
4531 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004532 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004533 // result will match the sign/zeroextendness of the result.
4534 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004535 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004536 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004537
4538 // If this is a cast from 'float -> double -> integer', cast from
4539 // 'float -> integer' directly, as the value isn't changed by the
4540 // float->double conversion.
4541 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4542 DstTy->isIntegral() &&
4543 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4544 return true;
4545
Chris Lattnercaba72b2006-04-02 05:43:13 +00004546 // Packed type conversions don't modify bits.
4547 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
4548 return true;
4549
Chris Lattner48a44f72002-05-02 17:06:02 +00004550 return false;
4551}
4552
Chris Lattner11ffd592004-07-20 05:21:00 +00004553static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004554 if (V->getType() == Ty || isa<Constant>(V)) return false;
4555 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004556 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4557 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004558 return false;
4559 return true;
4560}
4561
4562/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4563/// InsertBefore instruction. This is specialized a bit to avoid inserting
4564/// casts that are known to not do anything...
4565///
4566Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4567 Instruction *InsertBefore) {
4568 if (V->getType() == DestTy) return V;
4569 if (Constant *C = dyn_cast<Constant>(V))
4570 return ConstantExpr::getCast(C, DestTy);
4571
4572 CastInst *CI = new CastInst(V, DestTy, V->getName());
4573 InsertNewInstBefore(CI, *InsertBefore);
4574 return CI;
4575}
Chris Lattner48a44f72002-05-02 17:06:02 +00004576
Chris Lattner8f663e82005-10-29 04:36:15 +00004577/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4578/// expression. If so, decompose it, returning some value X, such that Val is
4579/// X*Scale+Offset.
4580///
4581static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4582 unsigned &Offset) {
4583 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4584 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4585 Offset = CI->getValue();
4586 Scale = 1;
4587 return ConstantUInt::get(Type::UIntTy, 0);
4588 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4589 if (I->getNumOperands() == 2) {
4590 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4591 if (I->getOpcode() == Instruction::Shl) {
4592 // This is a value scaled by '1 << the shift amt'.
4593 Scale = 1U << CUI->getValue();
4594 Offset = 0;
4595 return I->getOperand(0);
4596 } else if (I->getOpcode() == Instruction::Mul) {
4597 // This value is scaled by 'CUI'.
4598 Scale = CUI->getValue();
4599 Offset = 0;
4600 return I->getOperand(0);
4601 } else if (I->getOpcode() == Instruction::Add) {
4602 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4603 // divisible by C2.
4604 unsigned SubScale;
4605 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4606 Offset);
4607 Offset += CUI->getValue();
4608 if (SubScale > 1 && (Offset % SubScale == 0)) {
4609 Scale = SubScale;
4610 return SubVal;
4611 }
4612 }
4613 }
4614 }
4615 }
4616
4617 // Otherwise, we can't look past this.
4618 Scale = 1;
4619 Offset = 0;
4620 return Val;
4621}
4622
4623
Chris Lattner216be912005-10-24 06:03:58 +00004624/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4625/// try to eliminate the cast by moving the type information into the alloc.
4626Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4627 AllocationInst &AI) {
4628 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004629 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004630
Chris Lattnerac87beb2005-10-24 06:22:12 +00004631 // Remove any uses of AI that are dead.
4632 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4633 std::vector<Instruction*> DeadUsers;
4634 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4635 Instruction *User = cast<Instruction>(*UI++);
4636 if (isInstructionTriviallyDead(User)) {
4637 while (UI != E && *UI == User)
4638 ++UI; // If this instruction uses AI more than once, don't break UI.
4639
4640 // Add operands to the worklist.
4641 AddUsesToWorkList(*User);
4642 ++NumDeadInst;
4643 DEBUG(std::cerr << "IC: DCE: " << *User);
4644
4645 User->eraseFromParent();
4646 removeFromWorkList(User);
4647 }
4648 }
4649
Chris Lattner216be912005-10-24 06:03:58 +00004650 // Get the type really allocated and the type casted to.
4651 const Type *AllocElTy = AI.getAllocatedType();
4652 const Type *CastElTy = PTy->getElementType();
4653 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004654
4655 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4656 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4657 if (CastElTyAlign < AllocElTyAlign) return 0;
4658
Chris Lattner46705b22005-10-24 06:35:18 +00004659 // If the allocation has multiple uses, only promote it if we are strictly
4660 // increasing the alignment of the resultant allocation. If we keep it the
4661 // same, we open the door to infinite loops of various kinds.
4662 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4663
Chris Lattner216be912005-10-24 06:03:58 +00004664 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4665 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004666 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004667
Chris Lattner8270c332005-10-29 03:19:53 +00004668 // See if we can satisfy the modulus by pulling a scale out of the array
4669 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004670 unsigned ArraySizeScale, ArrayOffset;
4671 Value *NumElements = // See if the array size is a decomposable linear expr.
4672 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4673
Chris Lattner8270c332005-10-29 03:19:53 +00004674 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4675 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004676 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4677 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004678
Chris Lattner8270c332005-10-29 03:19:53 +00004679 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4680 Value *Amt = 0;
4681 if (Scale == 1) {
4682 Amt = NumElements;
4683 } else {
4684 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4685 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4686 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4687 else if (Scale != 1) {
4688 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4689 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004690 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004691 }
4692
Chris Lattner8f663e82005-10-29 04:36:15 +00004693 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4694 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4695 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4696 Amt = InsertNewInstBefore(Tmp, AI);
4697 }
4698
Chris Lattner216be912005-10-24 06:03:58 +00004699 std::string Name = AI.getName(); AI.setName("");
4700 AllocationInst *New;
4701 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004702 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004703 else
Nate Begeman848622f2005-11-05 09:21:28 +00004704 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004705 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004706
4707 // If the allocation has multiple uses, insert a cast and change all things
4708 // that used it to use the new cast. This will also hack on CI, but it will
4709 // die soon.
4710 if (!AI.hasOneUse()) {
4711 AddUsesToWorkList(AI);
4712 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4713 InsertNewInstBefore(NewCast, AI);
4714 AI.replaceAllUsesWith(NewCast);
4715 }
Chris Lattner216be912005-10-24 06:03:58 +00004716 return ReplaceInstUsesWith(CI, New);
4717}
4718
4719
Chris Lattner48a44f72002-05-02 17:06:02 +00004720// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004721//
Chris Lattner113f4f42002-06-25 16:13:24 +00004722Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004723 Value *Src = CI.getOperand(0);
4724
Chris Lattner48a44f72002-05-02 17:06:02 +00004725 // If the user is casting a value to the same type, eliminate this cast
4726 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004727 if (CI.getType() == Src->getType())
4728 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004729
Chris Lattner81a7a232004-10-16 18:11:37 +00004730 if (isa<UndefValue>(Src)) // cast undef -> undef
4731 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4732
Chris Lattner48a44f72002-05-02 17:06:02 +00004733 // If casting the result of another cast instruction, try to eliminate this
4734 // one!
4735 //
Chris Lattner86102b82005-01-01 16:22:27 +00004736 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4737 Value *A = CSrc->getOperand(0);
4738 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4739 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004740 // This instruction now refers directly to the cast's src operand. This
4741 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004742 CI.setOperand(0, CSrc->getOperand(0));
4743 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004744 }
4745
Chris Lattner650b6da2002-08-02 20:00:25 +00004746 // If this is an A->B->A cast, and we are dealing with integral types, try
4747 // to convert this into a logical 'and' instruction.
4748 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004749 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004750 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004751 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004752 CSrc->getType()->getPrimitiveSizeInBits() <
4753 CI.getType()->getPrimitiveSizeInBits()&&
4754 A->getType()->getPrimitiveSizeInBits() ==
4755 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004756 assert(CSrc->getType() != Type::ULongTy &&
4757 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004758 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004759 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4760 AndValue);
4761 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4762 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4763 if (And->getType() != CI.getType()) {
4764 And->setName(CSrc->getName()+".mask");
4765 InsertNewInstBefore(And, CI);
4766 And = new CastInst(And, CI.getType());
4767 }
4768 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004769 }
4770 }
Chris Lattner2590e512006-02-07 06:56:34 +00004771
Chris Lattner03841652004-05-25 04:29:21 +00004772 // If this is a cast to bool, turn it into the appropriate setne instruction.
4773 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004774 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004775 Constant::getNullValue(CI.getOperand(0)->getType()));
4776
Chris Lattner2590e512006-02-07 06:56:34 +00004777 // See if we can simplify any instructions used by the LHS whose sole
4778 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004779 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4780 uint64_t KnownZero, KnownOne;
4781 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4782 KnownZero, KnownOne))
4783 return &CI;
4784 }
Chris Lattner2590e512006-02-07 06:56:34 +00004785
Chris Lattnerd0d51602003-06-21 23:12:02 +00004786 // If casting the result of a getelementptr instruction with no offset, turn
4787 // this into a cast of the original pointer!
4788 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004789 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004790 bool AllZeroOperands = true;
4791 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4792 if (!isa<Constant>(GEP->getOperand(i)) ||
4793 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4794 AllZeroOperands = false;
4795 break;
4796 }
4797 if (AllZeroOperands) {
4798 CI.setOperand(0, GEP->getOperand(0));
4799 return &CI;
4800 }
4801 }
4802
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004803 // If we are casting a malloc or alloca to a pointer to a type of the same
4804 // size, rewrite the allocation instruction to allocate the "right" type.
4805 //
4806 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004807 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4808 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004809
Chris Lattner86102b82005-01-01 16:22:27 +00004810 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4811 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4812 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004813 if (isa<PHINode>(Src))
4814 if (Instruction *NV = FoldOpIntoPhi(CI))
4815 return NV;
4816
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004817 // If the source value is an instruction with only this use, we can attempt to
4818 // propagate the cast into the instruction. Also, only handle integral types
4819 // for now.
4820 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004821 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004822 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4823 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004824 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4825 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004826
4827 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4828 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4829
4830 switch (SrcI->getOpcode()) {
4831 case Instruction::Add:
4832 case Instruction::Mul:
4833 case Instruction::And:
4834 case Instruction::Or:
4835 case Instruction::Xor:
4836 // If we are discarding information, or just changing the sign, rewrite.
4837 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4838 // Don't insert two casts if they cannot be eliminated. We allow two
4839 // casts to be inserted if the sizes are the same. This could only be
4840 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004841 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4842 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004843 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4844 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4845 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4846 ->getOpcode(), Op0c, Op1c);
4847 }
4848 }
Chris Lattner72086162005-05-06 02:07:39 +00004849
4850 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4851 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4852 Op1 == ConstantBool::True &&
4853 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4854 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4855 return BinaryOperator::createXor(New,
4856 ConstantInt::get(CI.getType(), 1));
4857 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004858 break;
4859 case Instruction::Shl:
4860 // Allow changing the sign of the source operand. Do not allow changing
4861 // the size of the shift, UNLESS the shift amount is a constant. We
4862 // mush not change variable sized shifts to a smaller size, because it
4863 // is undefined to shift more bits out than exist in the value.
4864 if (DestBitSize == SrcBitSize ||
4865 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4866 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4867 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4868 }
4869 break;
Chris Lattner87380412005-05-06 04:18:52 +00004870 case Instruction::Shr:
4871 // If this is a signed shr, and if all bits shifted in are about to be
4872 // truncated off, turn it into an unsigned shr to allow greater
4873 // simplifications.
4874 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4875 isa<ConstantInt>(Op1)) {
4876 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4877 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4878 // Convert to unsigned.
4879 Value *N1 = InsertOperandCastBefore(Op0,
4880 Op0->getType()->getUnsignedVersion(), &CI);
4881 // Insert the new shift, which is now unsigned.
4882 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4883 Op1, Src->getName()), CI);
4884 return new CastInst(N1, CI.getType());
4885 }
4886 }
4887 break;
4888
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004889 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00004890 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004891 // We if we are just checking for a seteq of a single bit and casting it
4892 // to an integer. If so, shift the bit to the appropriate place then
4893 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00004894 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004895 uint64_t Op1CV = Op1C->getZExtValue();
4896 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4897 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4898 // cast (X == 1) to int --> X iff X has only the low bit set.
4899 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4900 // cast (X != 0) to int --> X iff X has only the low bit set.
4901 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4902 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4903 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4904 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4905 // If Op1C some other power of two, convert:
4906 uint64_t KnownZero, KnownOne;
4907 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4908 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4909
4910 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4911 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4912 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4913 // (X&4) == 2 --> false
4914 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00004915 Constant *Res = ConstantBool::get(isSetNE);
4916 Res = ConstantExpr::getCast(Res, CI.getType());
4917 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004918 }
4919
4920 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4921 Value *In = Op0;
4922 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004923 // Perform an unsigned shr by shiftamt. Convert input to
4924 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00004925 if (In->getType()->isSigned())
4926 In = InsertNewInstBefore(new CastInst(In,
4927 In->getType()->getUnsignedVersion(), In->getName()),CI);
4928 // Insert the shift to put the result in the low bit.
4929 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004930 ConstantInt::get(Type::UByteTy, ShiftAmt),
4931 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004932 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004933
4934 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4935 Constant *One = ConstantInt::get(In->getType(), 1);
4936 In = BinaryOperator::createXor(In, One, "tmp");
4937 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004938 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004939
4940 if (CI.getType() == In->getType())
4941 return ReplaceInstUsesWith(CI, In);
4942 else
4943 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004944 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004945 }
4946 }
4947 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004948 }
4949 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004950
Chris Lattner260ab202002-04-18 17:39:14 +00004951 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004952}
4953
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004954/// GetSelectFoldableOperands - We want to turn code that looks like this:
4955/// %C = or %A, %B
4956/// %D = select %cond, %C, %A
4957/// into:
4958/// %C = select %cond, %B, 0
4959/// %D = or %A, %C
4960///
4961/// Assuming that the specified instruction is an operand to the select, return
4962/// a bitmask indicating which operands of this instruction are foldable if they
4963/// equal the other incoming value of the select.
4964///
4965static unsigned GetSelectFoldableOperands(Instruction *I) {
4966 switch (I->getOpcode()) {
4967 case Instruction::Add:
4968 case Instruction::Mul:
4969 case Instruction::And:
4970 case Instruction::Or:
4971 case Instruction::Xor:
4972 return 3; // Can fold through either operand.
4973 case Instruction::Sub: // Can only fold on the amount subtracted.
4974 case Instruction::Shl: // Can only fold on the shift amount.
4975 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004976 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004977 default:
4978 return 0; // Cannot fold
4979 }
4980}
4981
4982/// GetSelectFoldableConstant - For the same transformation as the previous
4983/// function, return the identity constant that goes into the select.
4984static Constant *GetSelectFoldableConstant(Instruction *I) {
4985 switch (I->getOpcode()) {
4986 default: assert(0 && "This cannot happen!"); abort();
4987 case Instruction::Add:
4988 case Instruction::Sub:
4989 case Instruction::Or:
4990 case Instruction::Xor:
4991 return Constant::getNullValue(I->getType());
4992 case Instruction::Shl:
4993 case Instruction::Shr:
4994 return Constant::getNullValue(Type::UByteTy);
4995 case Instruction::And:
4996 return ConstantInt::getAllOnesValue(I->getType());
4997 case Instruction::Mul:
4998 return ConstantInt::get(I->getType(), 1);
4999 }
5000}
5001
Chris Lattner411336f2005-01-19 21:50:18 +00005002/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5003/// have the same opcode and only one use each. Try to simplify this.
5004Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5005 Instruction *FI) {
5006 if (TI->getNumOperands() == 1) {
5007 // If this is a non-volatile load or a cast from the same type,
5008 // merge.
5009 if (TI->getOpcode() == Instruction::Cast) {
5010 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5011 return 0;
5012 } else {
5013 return 0; // unknown unary op.
5014 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005015
Chris Lattner411336f2005-01-19 21:50:18 +00005016 // Fold this by inserting a select from the input values.
5017 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5018 FI->getOperand(0), SI.getName()+".v");
5019 InsertNewInstBefore(NewSI, SI);
5020 return new CastInst(NewSI, TI->getType());
5021 }
5022
5023 // Only handle binary operators here.
5024 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5025 return 0;
5026
5027 // Figure out if the operations have any operands in common.
5028 Value *MatchOp, *OtherOpT, *OtherOpF;
5029 bool MatchIsOpZero;
5030 if (TI->getOperand(0) == FI->getOperand(0)) {
5031 MatchOp = TI->getOperand(0);
5032 OtherOpT = TI->getOperand(1);
5033 OtherOpF = FI->getOperand(1);
5034 MatchIsOpZero = true;
5035 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5036 MatchOp = TI->getOperand(1);
5037 OtherOpT = TI->getOperand(0);
5038 OtherOpF = FI->getOperand(0);
5039 MatchIsOpZero = false;
5040 } else if (!TI->isCommutative()) {
5041 return 0;
5042 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5043 MatchOp = TI->getOperand(0);
5044 OtherOpT = TI->getOperand(1);
5045 OtherOpF = FI->getOperand(0);
5046 MatchIsOpZero = true;
5047 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5048 MatchOp = TI->getOperand(1);
5049 OtherOpT = TI->getOperand(0);
5050 OtherOpF = FI->getOperand(1);
5051 MatchIsOpZero = true;
5052 } else {
5053 return 0;
5054 }
5055
5056 // If we reach here, they do have operations in common.
5057 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5058 OtherOpF, SI.getName()+".v");
5059 InsertNewInstBefore(NewSI, SI);
5060
5061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5062 if (MatchIsOpZero)
5063 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5064 else
5065 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5066 } else {
5067 if (MatchIsOpZero)
5068 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5069 else
5070 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5071 }
5072}
5073
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005074Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005075 Value *CondVal = SI.getCondition();
5076 Value *TrueVal = SI.getTrueValue();
5077 Value *FalseVal = SI.getFalseValue();
5078
5079 // select true, X, Y -> X
5080 // select false, X, Y -> Y
5081 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005082 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005083 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005084 else {
5085 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005086 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005087 }
Chris Lattner533bc492004-03-30 19:37:13 +00005088
5089 // select C, X, X -> X
5090 if (TrueVal == FalseVal)
5091 return ReplaceInstUsesWith(SI, TrueVal);
5092
Chris Lattner81a7a232004-10-16 18:11:37 +00005093 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5094 return ReplaceInstUsesWith(SI, FalseVal);
5095 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5096 return ReplaceInstUsesWith(SI, TrueVal);
5097 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5098 if (isa<Constant>(TrueVal))
5099 return ReplaceInstUsesWith(SI, TrueVal);
5100 else
5101 return ReplaceInstUsesWith(SI, FalseVal);
5102 }
5103
Chris Lattner1c631e82004-04-08 04:43:23 +00005104 if (SI.getType() == Type::BoolTy)
5105 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5106 if (C == ConstantBool::True) {
5107 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005108 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005109 } else {
5110 // Change: A = select B, false, C --> A = and !B, C
5111 Value *NotCond =
5112 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5113 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005114 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005115 }
5116 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5117 if (C == ConstantBool::False) {
5118 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005119 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005120 } else {
5121 // Change: A = select B, C, true --> A = or !B, C
5122 Value *NotCond =
5123 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5124 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005125 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005126 }
5127 }
5128
Chris Lattner183b3362004-04-09 19:05:30 +00005129 // Selecting between two integer constants?
5130 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5131 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5132 // select C, 1, 0 -> cast C to int
5133 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5134 return new CastInst(CondVal, SI.getType());
5135 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5136 // select C, 0, 1 -> cast !C to int
5137 Value *NotCond =
5138 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005139 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005140 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005141 }
Chris Lattner35167c32004-06-09 07:59:58 +00005142
5143 // If one of the constants is zero (we know they can't both be) and we
5144 // have a setcc instruction with zero, and we have an 'and' with the
5145 // non-constant value, eliminate this whole mess. This corresponds to
5146 // cases like this: ((X & 27) ? 27 : 0)
5147 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5148 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5149 if ((IC->getOpcode() == Instruction::SetEQ ||
5150 IC->getOpcode() == Instruction::SetNE) &&
5151 isa<ConstantInt>(IC->getOperand(1)) &&
5152 cast<Constant>(IC->getOperand(1))->isNullValue())
5153 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5154 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005155 isa<ConstantInt>(ICA->getOperand(1)) &&
5156 (ICA->getOperand(1) == TrueValC ||
5157 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005158 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5159 // Okay, now we know that everything is set up, we just don't
5160 // know whether we have a setne or seteq and whether the true or
5161 // false val is the zero.
5162 bool ShouldNotVal = !TrueValC->isNullValue();
5163 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5164 Value *V = ICA;
5165 if (ShouldNotVal)
5166 V = InsertNewInstBefore(BinaryOperator::create(
5167 Instruction::Xor, V, ICA->getOperand(1)), SI);
5168 return ReplaceInstUsesWith(SI, V);
5169 }
Chris Lattner533bc492004-03-30 19:37:13 +00005170 }
Chris Lattner623fba12004-04-10 22:21:27 +00005171
5172 // See if we are selecting two values based on a comparison of the two values.
5173 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5174 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5175 // Transform (X == Y) ? X : Y -> Y
5176 if (SCI->getOpcode() == Instruction::SetEQ)
5177 return ReplaceInstUsesWith(SI, FalseVal);
5178 // Transform (X != Y) ? X : Y -> X
5179 if (SCI->getOpcode() == Instruction::SetNE)
5180 return ReplaceInstUsesWith(SI, TrueVal);
5181 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5182
5183 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5184 // Transform (X == Y) ? Y : X -> X
5185 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005186 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005187 // Transform (X != Y) ? Y : X -> Y
5188 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005189 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005190 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5191 }
5192 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005193
Chris Lattnera04c9042005-01-13 22:52:24 +00005194 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5195 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5196 if (TI->hasOneUse() && FI->hasOneUse()) {
5197 bool isInverse = false;
5198 Instruction *AddOp = 0, *SubOp = 0;
5199
Chris Lattner411336f2005-01-19 21:50:18 +00005200 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5201 if (TI->getOpcode() == FI->getOpcode())
5202 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5203 return IV;
5204
5205 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5206 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005207 if (TI->getOpcode() == Instruction::Sub &&
5208 FI->getOpcode() == Instruction::Add) {
5209 AddOp = FI; SubOp = TI;
5210 } else if (FI->getOpcode() == Instruction::Sub &&
5211 TI->getOpcode() == Instruction::Add) {
5212 AddOp = TI; SubOp = FI;
5213 }
5214
5215 if (AddOp) {
5216 Value *OtherAddOp = 0;
5217 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5218 OtherAddOp = AddOp->getOperand(1);
5219 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5220 OtherAddOp = AddOp->getOperand(0);
5221 }
5222
5223 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005224 // So at this point we know we have (Y -> OtherAddOp):
5225 // select C, (add X, Y), (sub X, Z)
5226 Value *NegVal; // Compute -Z
5227 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5228 NegVal = ConstantExpr::getNeg(C);
5229 } else {
5230 NegVal = InsertNewInstBefore(
5231 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005232 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005233
5234 Value *NewTrueOp = OtherAddOp;
5235 Value *NewFalseOp = NegVal;
5236 if (AddOp != TI)
5237 std::swap(NewTrueOp, NewFalseOp);
5238 Instruction *NewSel =
5239 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5240
5241 NewSel = InsertNewInstBefore(NewSel, SI);
5242 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005243 }
5244 }
5245 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005246
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005247 // See if we can fold the select into one of our operands.
5248 if (SI.getType()->isInteger()) {
5249 // See the comment above GetSelectFoldableOperands for a description of the
5250 // transformation we are doing here.
5251 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5252 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5253 !isa<Constant>(FalseVal))
5254 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5255 unsigned OpToFold = 0;
5256 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5257 OpToFold = 1;
5258 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5259 OpToFold = 2;
5260 }
5261
5262 if (OpToFold) {
5263 Constant *C = GetSelectFoldableConstant(TVI);
5264 std::string Name = TVI->getName(); TVI->setName("");
5265 Instruction *NewSel =
5266 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5267 Name);
5268 InsertNewInstBefore(NewSel, SI);
5269 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5270 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5271 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5272 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5273 else {
5274 assert(0 && "Unknown instruction!!");
5275 }
5276 }
5277 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005278
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005279 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5280 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5281 !isa<Constant>(TrueVal))
5282 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5283 unsigned OpToFold = 0;
5284 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5285 OpToFold = 1;
5286 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5287 OpToFold = 2;
5288 }
5289
5290 if (OpToFold) {
5291 Constant *C = GetSelectFoldableConstant(FVI);
5292 std::string Name = FVI->getName(); FVI->setName("");
5293 Instruction *NewSel =
5294 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5295 Name);
5296 InsertNewInstBefore(NewSel, SI);
5297 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5298 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5299 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5300 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5301 else {
5302 assert(0 && "Unknown instruction!!");
5303 }
5304 }
5305 }
5306 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005307
5308 if (BinaryOperator::isNot(CondVal)) {
5309 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5310 SI.setOperand(1, FalseVal);
5311 SI.setOperand(2, TrueVal);
5312 return &SI;
5313 }
5314
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005315 return 0;
5316}
5317
Chris Lattner82f2ef22006-03-06 20:18:44 +00005318/// GetKnownAlignment - If the specified pointer has an alignment that we can
5319/// determine, return it, otherwise return 0.
5320static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5321 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5322 unsigned Align = GV->getAlignment();
5323 if (Align == 0 && TD)
5324 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5325 return Align;
5326 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5327 unsigned Align = AI->getAlignment();
5328 if (Align == 0 && TD) {
5329 if (isa<AllocaInst>(AI))
5330 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5331 else if (isa<MallocInst>(AI)) {
5332 // Malloc returns maximally aligned memory.
5333 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5334 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5335 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5336 }
5337 }
5338 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005339 } else if (isa<CastInst>(V) ||
5340 (isa<ConstantExpr>(V) &&
5341 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5342 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005343 if (isa<PointerType>(CI->getOperand(0)->getType()))
5344 return GetKnownAlignment(CI->getOperand(0), TD);
5345 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005346 } else if (isa<GetElementPtrInst>(V) ||
5347 (isa<ConstantExpr>(V) &&
5348 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5349 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005350 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5351 if (BaseAlignment == 0) return 0;
5352
5353 // If all indexes are zero, it is just the alignment of the base pointer.
5354 bool AllZeroOperands = true;
5355 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5356 if (!isa<Constant>(GEPI->getOperand(i)) ||
5357 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5358 AllZeroOperands = false;
5359 break;
5360 }
5361 if (AllZeroOperands)
5362 return BaseAlignment;
5363
5364 // Otherwise, if the base alignment is >= the alignment we expect for the
5365 // base pointer type, then we know that the resultant pointer is aligned at
5366 // least as much as its type requires.
5367 if (!TD) return 0;
5368
5369 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5370 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005371 <= BaseAlignment) {
5372 const Type *GEPTy = GEPI->getType();
5373 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5374 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005375 return 0;
5376 }
5377 return 0;
5378}
5379
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005380
Chris Lattnerc66b2232006-01-13 20:11:04 +00005381/// visitCallInst - CallInst simplification. This mostly only handles folding
5382/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5383/// the heavy lifting.
5384///
Chris Lattner970c33a2003-06-19 17:00:31 +00005385Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005386 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5387 if (!II) return visitCallSite(&CI);
5388
Chris Lattner51ea1272004-02-28 05:22:00 +00005389 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5390 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005391 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005392 bool Changed = false;
5393
5394 // memmove/cpy/set of zero bytes is a noop.
5395 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5396 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5397
Chris Lattner00648e12004-10-12 04:52:52 +00005398 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5399 if (CI->getRawValue() == 1) {
5400 // Replace the instruction with just byte operations. We would
5401 // transform other cases to loads/stores, but we don't know if
5402 // alignment is sufficient.
5403 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005404 }
5405
Chris Lattner00648e12004-10-12 04:52:52 +00005406 // If we have a memmove and the source operation is a constant global,
5407 // then the source and dest pointers can't alias, so we can change this
5408 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005409 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005410 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5411 if (GVSrc->isConstant()) {
5412 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005413 const char *Name;
5414 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5415 Type::UIntTy)
5416 Name = "llvm.memcpy.i32";
5417 else
5418 Name = "llvm.memcpy.i64";
5419 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00005420 CI.getCalledFunction()->getFunctionType());
5421 CI.setOperand(0, MemCpy);
5422 Changed = true;
5423 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005424 }
Chris Lattner00648e12004-10-12 04:52:52 +00005425
Chris Lattner82f2ef22006-03-06 20:18:44 +00005426 // If we can determine a pointer alignment that is bigger than currently
5427 // set, update the alignment.
5428 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5429 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5430 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5431 unsigned Align = std::min(Alignment1, Alignment2);
5432 if (MI->getAlignment()->getRawValue() < Align) {
5433 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5434 Changed = true;
5435 }
5436 } else if (isa<MemSetInst>(MI)) {
5437 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5438 if (MI->getAlignment()->getRawValue() < Alignment) {
5439 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5440 Changed = true;
5441 }
5442 }
5443
Chris Lattnerc66b2232006-01-13 20:11:04 +00005444 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00005445 } else {
5446 switch (II->getIntrinsicID()) {
5447 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005448 case Intrinsic::ppc_altivec_lvx:
5449 case Intrinsic::ppc_altivec_lvxl:
5450 // Turn lvx -> load if the pointer is known aligned.
5451 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005452 Value *Ptr = InsertCastBefore(II->getOperand(1),
5453 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005454 return new LoadInst(Ptr);
5455 }
5456 break;
5457 case Intrinsic::ppc_altivec_stvx:
5458 case Intrinsic::ppc_altivec_stvxl:
5459 // Turn stvx -> store if the pointer is known aligned.
5460 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005461 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5462 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005463 return new StoreInst(II->getOperand(1), Ptr);
5464 }
5465 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00005466 case Intrinsic::ppc_altivec_vperm:
5467 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5468 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5469 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5470
5471 // Check that all of the elements are integer constants or undefs.
5472 bool AllEltsOk = true;
5473 for (unsigned i = 0; i != 16; ++i) {
5474 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5475 !isa<UndefValue>(Mask->getOperand(i))) {
5476 AllEltsOk = false;
5477 break;
5478 }
5479 }
5480
5481 if (AllEltsOk) {
5482 // Cast the input vectors to byte vectors.
5483 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5484 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5485 Value *Result = UndefValue::get(Op0->getType());
5486
5487 // Only extract each element once.
5488 Value *ExtractedElts[32];
5489 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5490
5491 for (unsigned i = 0; i != 16; ++i) {
5492 if (isa<UndefValue>(Mask->getOperand(i)))
5493 continue;
5494 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5495 Idx &= 31; // Match the hardware behavior.
5496
5497 if (ExtractedElts[Idx] == 0) {
5498 Instruction *Elt =
5499 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5500 ConstantUInt::get(Type::UIntTy, Idx&15),
5501 "tmp");
5502 InsertNewInstBefore(Elt, CI);
5503 ExtractedElts[Idx] = Elt;
5504 }
5505
5506 // Insert this value into the result vector.
5507 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5508 ConstantUInt::get(Type::UIntTy, i),
5509 "tmp");
5510 InsertNewInstBefore(cast<Instruction>(Result), CI);
5511 }
5512 return new CastInst(Result, CI.getType());
5513 }
5514 }
5515 break;
5516
Chris Lattner503221f2006-01-13 21:28:09 +00005517 case Intrinsic::stackrestore: {
5518 // If the save is right next to the restore, remove the restore. This can
5519 // happen when variable allocas are DCE'd.
5520 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5521 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5522 BasicBlock::iterator BI = SS;
5523 if (&*++BI == II)
5524 return EraseInstFromFunction(CI);
5525 }
5526 }
5527
5528 // If the stack restore is in a return/unwind block and if there are no
5529 // allocas or calls between the restore and the return, nuke the restore.
5530 TerminatorInst *TI = II->getParent()->getTerminator();
5531 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5532 BasicBlock::iterator BI = II;
5533 bool CannotRemove = false;
5534 for (++BI; &*BI != TI; ++BI) {
5535 if (isa<AllocaInst>(BI) ||
5536 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5537 CannotRemove = true;
5538 break;
5539 }
5540 }
5541 if (!CannotRemove)
5542 return EraseInstFromFunction(CI);
5543 }
5544 break;
5545 }
5546 }
Chris Lattner00648e12004-10-12 04:52:52 +00005547 }
5548
Chris Lattnerc66b2232006-01-13 20:11:04 +00005549 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005550}
5551
5552// InvokeInst simplification
5553//
5554Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005555 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005556}
5557
Chris Lattneraec3d942003-10-07 22:32:43 +00005558// visitCallSite - Improvements for call and invoke instructions.
5559//
5560Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005561 bool Changed = false;
5562
5563 // If the callee is a constexpr cast of a function, attempt to move the cast
5564 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005565 if (transformConstExprCastCall(CS)) return 0;
5566
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005567 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005568
Chris Lattner61d9d812005-05-13 07:09:09 +00005569 if (Function *CalleeF = dyn_cast<Function>(Callee))
5570 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5571 Instruction *OldCall = CS.getInstruction();
5572 // If the call and callee calling conventions don't match, this call must
5573 // be unreachable, as the call is undefined.
5574 new StoreInst(ConstantBool::True,
5575 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5576 if (!OldCall->use_empty())
5577 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5578 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5579 return EraseInstFromFunction(*OldCall);
5580 return 0;
5581 }
5582
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005583 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5584 // This instruction is not reachable, just remove it. We insert a store to
5585 // undef so that we know that this code is not reachable, despite the fact
5586 // that we can't modify the CFG here.
5587 new StoreInst(ConstantBool::True,
5588 UndefValue::get(PointerType::get(Type::BoolTy)),
5589 CS.getInstruction());
5590
5591 if (!CS.getInstruction()->use_empty())
5592 CS.getInstruction()->
5593 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5594
5595 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5596 // Don't break the CFG, insert a dummy cond branch.
5597 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5598 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005599 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005600 return EraseInstFromFunction(*CS.getInstruction());
5601 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005602
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005603 const PointerType *PTy = cast<PointerType>(Callee->getType());
5604 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5605 if (FTy->isVarArg()) {
5606 // See if we can optimize any arguments passed through the varargs area of
5607 // the call.
5608 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5609 E = CS.arg_end(); I != E; ++I)
5610 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5611 // If this cast does not effect the value passed through the varargs
5612 // area, we can eliminate the use of the cast.
5613 Value *Op = CI->getOperand(0);
5614 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5615 *I = Op;
5616 Changed = true;
5617 }
5618 }
5619 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005620
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005621 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005622}
5623
Chris Lattner970c33a2003-06-19 17:00:31 +00005624// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5625// attempt to move the cast to the arguments of the call/invoke.
5626//
5627bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5628 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5629 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005630 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005631 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005632 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005633 Instruction *Caller = CS.getInstruction();
5634
5635 // Okay, this is a cast from a function to a different type. Unless doing so
5636 // would cause a type conversion of one of our arguments, change this call to
5637 // be a direct call with arguments casted to the appropriate types.
5638 //
5639 const FunctionType *FT = Callee->getFunctionType();
5640 const Type *OldRetTy = Caller->getType();
5641
Chris Lattner1f7942f2004-01-14 06:06:08 +00005642 // Check to see if we are changing the return type...
5643 if (OldRetTy != FT->getReturnType()) {
5644 if (Callee->isExternal() &&
5645 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5646 !Caller->use_empty())
5647 return false; // Cannot transform this return value...
5648
5649 // If the callsite is an invoke instruction, and the return value is used by
5650 // a PHI node in a successor, we cannot change the return type of the call
5651 // because there is no place to put the cast instruction (without breaking
5652 // the critical edge). Bail out in this case.
5653 if (!Caller->use_empty())
5654 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5655 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5656 UI != E; ++UI)
5657 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5658 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005659 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005660 return false;
5661 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005662
5663 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5664 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005665
Chris Lattner970c33a2003-06-19 17:00:31 +00005666 CallSite::arg_iterator AI = CS.arg_begin();
5667 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5668 const Type *ParamTy = FT->getParamType(i);
5669 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005670 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005671 }
5672
5673 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5674 Callee->isExternal())
5675 return false; // Do not delete arguments unless we have a function body...
5676
5677 // Okay, we decided that this is a safe thing to do: go ahead and start
5678 // inserting cast instructions as necessary...
5679 std::vector<Value*> Args;
5680 Args.reserve(NumActualArgs);
5681
5682 AI = CS.arg_begin();
5683 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5684 const Type *ParamTy = FT->getParamType(i);
5685 if ((*AI)->getType() == ParamTy) {
5686 Args.push_back(*AI);
5687 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005688 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5689 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005690 }
5691 }
5692
5693 // If the function takes more arguments than the call was taking, add them
5694 // now...
5695 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5696 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5697
5698 // If we are removing arguments to the function, emit an obnoxious warning...
5699 if (FT->getNumParams() < NumActualArgs)
5700 if (!FT->isVarArg()) {
5701 std::cerr << "WARNING: While resolving call to function '"
5702 << Callee->getName() << "' arguments were dropped!\n";
5703 } else {
5704 // Add all of the arguments in their promoted form to the arg list...
5705 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5706 const Type *PTy = getPromotedType((*AI)->getType());
5707 if (PTy != (*AI)->getType()) {
5708 // Must promote to pass through va_arg area!
5709 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5710 InsertNewInstBefore(Cast, *Caller);
5711 Args.push_back(Cast);
5712 } else {
5713 Args.push_back(*AI);
5714 }
5715 }
5716 }
5717
5718 if (FT->getReturnType() == Type::VoidTy)
5719 Caller->setName(""); // Void type should not have a name...
5720
5721 Instruction *NC;
5722 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005723 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005724 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005725 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005726 } else {
5727 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005728 if (cast<CallInst>(Caller)->isTailCall())
5729 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005730 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005731 }
5732
5733 // Insert a cast of the return type as necessary...
5734 Value *NV = NC;
5735 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5736 if (NV->getType() != Type::VoidTy) {
5737 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005738
5739 // If this is an invoke instruction, we should insert it after the first
5740 // non-phi, instruction in the normal successor block.
5741 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5742 BasicBlock::iterator I = II->getNormalDest()->begin();
5743 while (isa<PHINode>(I)) ++I;
5744 InsertNewInstBefore(NC, *I);
5745 } else {
5746 // Otherwise, it's a call, just insert cast right after the call instr
5747 InsertNewInstBefore(NC, *Caller);
5748 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005749 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005750 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005751 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005752 }
5753 }
5754
5755 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5756 Caller->replaceAllUsesWith(NV);
5757 Caller->getParent()->getInstList().erase(Caller);
5758 removeFromWorkList(Caller);
5759 return true;
5760}
5761
5762
Chris Lattner7515cab2004-11-14 19:13:23 +00005763// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5764// operator and they all are only used by the PHI, PHI together their
5765// inputs, and do the operation once, to the result of the PHI.
5766Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5767 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5768
5769 // Scan the instruction, looking for input operations that can be folded away.
5770 // If all input operands to the phi are the same instruction (e.g. a cast from
5771 // the same type or "+42") we can pull the operation through the PHI, reducing
5772 // code size and simplifying code.
5773 Constant *ConstantOp = 0;
5774 const Type *CastSrcTy = 0;
5775 if (isa<CastInst>(FirstInst)) {
5776 CastSrcTy = FirstInst->getOperand(0)->getType();
5777 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5778 // Can fold binop or shift if the RHS is a constant.
5779 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5780 if (ConstantOp == 0) return 0;
5781 } else {
5782 return 0; // Cannot fold this operation.
5783 }
5784
5785 // Check to see if all arguments are the same operation.
5786 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5787 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5788 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5789 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5790 return 0;
5791 if (CastSrcTy) {
5792 if (I->getOperand(0)->getType() != CastSrcTy)
5793 return 0; // Cast operation must match.
5794 } else if (I->getOperand(1) != ConstantOp) {
5795 return 0;
5796 }
5797 }
5798
5799 // Okay, they are all the same operation. Create a new PHI node of the
5800 // correct type, and PHI together all of the LHS's of the instructions.
5801 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5802 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005803 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005804
5805 Value *InVal = FirstInst->getOperand(0);
5806 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005807
5808 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005809 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5810 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5811 if (NewInVal != InVal)
5812 InVal = 0;
5813 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5814 }
5815
5816 Value *PhiVal;
5817 if (InVal) {
5818 // The new PHI unions all of the same values together. This is really
5819 // common, so we handle it intelligently here for compile-time speed.
5820 PhiVal = InVal;
5821 delete NewPN;
5822 } else {
5823 InsertNewInstBefore(NewPN, PN);
5824 PhiVal = NewPN;
5825 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005826
Chris Lattner7515cab2004-11-14 19:13:23 +00005827 // Insert and return the new operation.
5828 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005829 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005830 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005831 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005832 else
5833 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005834 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005835}
Chris Lattner48a44f72002-05-02 17:06:02 +00005836
Chris Lattner71536432005-01-17 05:10:15 +00005837/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5838/// that is dead.
5839static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5840 if (PN->use_empty()) return true;
5841 if (!PN->hasOneUse()) return false;
5842
5843 // Remember this node, and if we find the cycle, return.
5844 if (!PotentiallyDeadPHIs.insert(PN).second)
5845 return true;
5846
5847 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5848 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005849
Chris Lattner71536432005-01-17 05:10:15 +00005850 return false;
5851}
5852
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005853// PHINode simplification
5854//
Chris Lattner113f4f42002-06-25 16:13:24 +00005855Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005856 if (Value *V = PN.hasConstantValue())
5857 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005858
5859 // If the only user of this instruction is a cast instruction, and all of the
5860 // incoming values are constants, change this PHI to merge together the casted
5861 // constants.
5862 if (PN.hasOneUse())
5863 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5864 if (CI->getType() != PN.getType()) { // noop casts will be folded
5865 bool AllConstant = true;
5866 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5867 if (!isa<Constant>(PN.getIncomingValue(i))) {
5868 AllConstant = false;
5869 break;
5870 }
5871 if (AllConstant) {
5872 // Make a new PHI with all casted values.
5873 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5874 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5875 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5876 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5877 PN.getIncomingBlock(i));
5878 }
5879
5880 // Update the cast instruction.
5881 CI->setOperand(0, New);
5882 WorkList.push_back(CI); // revisit the cast instruction to fold.
5883 WorkList.push_back(New); // Make sure to revisit the new Phi
5884 return &PN; // PN is now dead!
5885 }
5886 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005887
5888 // If all PHI operands are the same operation, pull them through the PHI,
5889 // reducing code size.
5890 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5891 PN.getIncomingValue(0)->hasOneUse())
5892 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5893 return Result;
5894
Chris Lattner71536432005-01-17 05:10:15 +00005895 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5896 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5897 // PHI)... break the cycle.
5898 if (PN.hasOneUse())
5899 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5900 std::set<PHINode*> PotentiallyDeadPHIs;
5901 PotentiallyDeadPHIs.insert(&PN);
5902 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5903 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5904 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005905
Chris Lattner91daeb52003-12-19 05:58:40 +00005906 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005907}
5908
Chris Lattner69193f92004-04-05 01:30:19 +00005909static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5910 Instruction *InsertPoint,
5911 InstCombiner *IC) {
5912 unsigned PS = IC->getTargetData().getPointerSize();
5913 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005914 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5915 // We must insert a cast to ensure we sign-extend.
5916 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5917 V->getName()), *InsertPoint);
5918 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5919 *InsertPoint);
5920}
5921
Chris Lattner48a44f72002-05-02 17:06:02 +00005922
Chris Lattner113f4f42002-06-25 16:13:24 +00005923Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005924 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005925 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005926 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005927 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005928 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005929
Chris Lattner81a7a232004-10-16 18:11:37 +00005930 if (isa<UndefValue>(GEP.getOperand(0)))
5931 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5932
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005933 bool HasZeroPointerIndex = false;
5934 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5935 HasZeroPointerIndex = C->isNullValue();
5936
5937 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005938 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005939
Chris Lattner69193f92004-04-05 01:30:19 +00005940 // Eliminate unneeded casts for indices.
5941 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005942 gep_type_iterator GTI = gep_type_begin(GEP);
5943 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5944 if (isa<SequentialType>(*GTI)) {
5945 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5946 Value *Src = CI->getOperand(0);
5947 const Type *SrcTy = Src->getType();
5948 const Type *DestTy = CI->getType();
5949 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005950 if (SrcTy->getPrimitiveSizeInBits() ==
5951 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005952 // We can always eliminate a cast from ulong or long to the other.
5953 // We can always eliminate a cast from uint to int or the other on
5954 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005955 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005956 MadeChange = true;
5957 GEP.setOperand(i, Src);
5958 }
5959 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5960 SrcTy->getPrimitiveSize() == 4) {
5961 // We can always eliminate a cast from int to [u]long. We can
5962 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5963 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005964 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005965 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005966 MadeChange = true;
5967 GEP.setOperand(i, Src);
5968 }
Chris Lattner69193f92004-04-05 01:30:19 +00005969 }
5970 }
5971 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005972 // If we are using a wider index than needed for this platform, shrink it
5973 // to what we need. If the incoming value needs a cast instruction,
5974 // insert it. This explicit cast can make subsequent optimizations more
5975 // obvious.
5976 Value *Op = GEP.getOperand(i);
5977 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005978 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005979 GEP.setOperand(i, ConstantExpr::getCast(C,
5980 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005981 MadeChange = true;
5982 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005983 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5984 Op->getName()), GEP);
5985 GEP.setOperand(i, Op);
5986 MadeChange = true;
5987 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005988
5989 // If this is a constant idx, make sure to canonicalize it to be a signed
5990 // operand, otherwise CSE and other optimizations are pessimized.
5991 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5992 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5993 CUI->getType()->getSignedVersion()));
5994 MadeChange = true;
5995 }
Chris Lattner69193f92004-04-05 01:30:19 +00005996 }
5997 if (MadeChange) return &GEP;
5998
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005999 // Combine Indices - If the source pointer to this getelementptr instruction
6000 // is a getelementptr instruction, combine the indices of the two
6001 // getelementptr instructions into a single instruction.
6002 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006003 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006004 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006005 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006006
6007 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006008 // Note that if our source is a gep chain itself that we wait for that
6009 // chain to be resolved before we perform this transformation. This
6010 // avoids us creating a TON of code in some cases.
6011 //
6012 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6013 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6014 return 0; // Wait until our source is folded to completion.
6015
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006016 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006017
6018 // Find out whether the last index in the source GEP is a sequential idx.
6019 bool EndsWithSequential = false;
6020 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6021 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006022 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006023
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006024 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006025 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006026 // Replace: gep (gep %P, long B), long A, ...
6027 // With: T = long A+B; gep %P, T, ...
6028 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006029 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006030 if (SO1 == Constant::getNullValue(SO1->getType())) {
6031 Sum = GO1;
6032 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6033 Sum = SO1;
6034 } else {
6035 // If they aren't the same type, convert both to an integer of the
6036 // target's pointer size.
6037 if (SO1->getType() != GO1->getType()) {
6038 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6039 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6040 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6041 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6042 } else {
6043 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006044 if (SO1->getType()->getPrimitiveSize() == PS) {
6045 // Convert GO1 to SO1's type.
6046 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6047
6048 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6049 // Convert SO1 to GO1's type.
6050 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6051 } else {
6052 const Type *PT = TD->getIntPtrType();
6053 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6054 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6055 }
6056 }
6057 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006058 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6059 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6060 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006061 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6062 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006063 }
Chris Lattner69193f92004-04-05 01:30:19 +00006064 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006065
6066 // Recycle the GEP we already have if possible.
6067 if (SrcGEPOperands.size() == 2) {
6068 GEP.setOperand(0, SrcGEPOperands[0]);
6069 GEP.setOperand(1, Sum);
6070 return &GEP;
6071 } else {
6072 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6073 SrcGEPOperands.end()-1);
6074 Indices.push_back(Sum);
6075 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6076 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006077 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006078 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006079 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006080 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006081 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6082 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006083 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6084 }
6085
6086 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006087 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006088
Chris Lattner5f667a62004-05-07 22:09:22 +00006089 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006090 // GEP of global variable. If all of the indices for this GEP are
6091 // constants, we can promote this to a constexpr instead of an instruction.
6092
6093 // Scan for nonconstants...
6094 std::vector<Constant*> Indices;
6095 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6096 for (; I != E && isa<Constant>(*I); ++I)
6097 Indices.push_back(cast<Constant>(*I));
6098
6099 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006100 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006101
6102 // Replace all uses of the GEP with the new constexpr...
6103 return ReplaceInstUsesWith(GEP, CE);
6104 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006105 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6106 if (!isa<PointerType>(X->getType())) {
6107 // Not interesting. Source pointer must be a cast from pointer.
6108 } else if (HasZeroPointerIndex) {
6109 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6110 // into : GEP [10 x ubyte]* X, long 0, ...
6111 //
6112 // This occurs when the program declares an array extern like "int X[];"
6113 //
6114 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6115 const PointerType *XTy = cast<PointerType>(X->getType());
6116 if (const ArrayType *XATy =
6117 dyn_cast<ArrayType>(XTy->getElementType()))
6118 if (const ArrayType *CATy =
6119 dyn_cast<ArrayType>(CPTy->getElementType()))
6120 if (CATy->getElementType() == XATy->getElementType()) {
6121 // At this point, we know that the cast source type is a pointer
6122 // to an array of the same type as the destination pointer
6123 // array. Because the array type is never stepped over (there
6124 // is a leading zero) we can fold the cast into this GEP.
6125 GEP.setOperand(0, X);
6126 return &GEP;
6127 }
6128 } else if (GEP.getNumOperands() == 2) {
6129 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006130 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6131 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006132 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6133 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6134 if (isa<ArrayType>(SrcElTy) &&
6135 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6136 TD->getTypeSize(ResElTy)) {
6137 Value *V = InsertNewInstBefore(
6138 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6139 GEP.getOperand(1), GEP.getName()), GEP);
6140 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006141 }
Chris Lattner2a893292005-09-13 18:36:04 +00006142
6143 // Transform things like:
6144 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6145 // (where tmp = 8*tmp2) into:
6146 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6147
6148 if (isa<ArrayType>(SrcElTy) &&
6149 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6150 uint64_t ArrayEltSize =
6151 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6152
6153 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6154 // allow either a mul, shift, or constant here.
6155 Value *NewIdx = 0;
6156 ConstantInt *Scale = 0;
6157 if (ArrayEltSize == 1) {
6158 NewIdx = GEP.getOperand(1);
6159 Scale = ConstantInt::get(NewIdx->getType(), 1);
6160 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006161 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006162 Scale = CI;
6163 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6164 if (Inst->getOpcode() == Instruction::Shl &&
6165 isa<ConstantInt>(Inst->getOperand(1))) {
6166 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6167 if (Inst->getType()->isSigned())
6168 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6169 else
6170 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6171 NewIdx = Inst->getOperand(0);
6172 } else if (Inst->getOpcode() == Instruction::Mul &&
6173 isa<ConstantInt>(Inst->getOperand(1))) {
6174 Scale = cast<ConstantInt>(Inst->getOperand(1));
6175 NewIdx = Inst->getOperand(0);
6176 }
6177 }
6178
6179 // If the index will be to exactly the right offset with the scale taken
6180 // out, perform the transformation.
6181 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6182 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6183 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006184 (int64_t)C->getRawValue() /
6185 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006186 else
6187 Scale = ConstantUInt::get(Scale->getType(),
6188 Scale->getRawValue() / ArrayEltSize);
6189 if (Scale->getRawValue() != 1) {
6190 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6191 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6192 NewIdx = InsertNewInstBefore(Sc, GEP);
6193 }
6194
6195 // Insert the new GEP instruction.
6196 Instruction *Idx =
6197 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6198 NewIdx, GEP.getName());
6199 Idx = InsertNewInstBefore(Idx, GEP);
6200 return new CastInst(Idx, GEP.getType());
6201 }
6202 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006203 }
Chris Lattnerca081252001-12-14 16:52:21 +00006204 }
6205
Chris Lattnerca081252001-12-14 16:52:21 +00006206 return 0;
6207}
6208
Chris Lattner1085bdf2002-11-04 16:18:53 +00006209Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6210 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6211 if (AI.isArrayAllocation()) // Check C != 1
6212 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6213 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006214 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006215
6216 // Create and insert the replacement instruction...
6217 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006218 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006219 else {
6220 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006221 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006222 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006223
6224 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006225
Chris Lattner1085bdf2002-11-04 16:18:53 +00006226 // Scan to the end of the allocation instructions, to skip over a block of
6227 // allocas if possible...
6228 //
6229 BasicBlock::iterator It = New;
6230 while (isa<AllocationInst>(*It)) ++It;
6231
6232 // Now that I is pointing to the first non-allocation-inst in the block,
6233 // insert our getelementptr instruction...
6234 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006235 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6236 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6237 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006238
6239 // Now make everything use the getelementptr instead of the original
6240 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006241 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006242 } else if (isa<UndefValue>(AI.getArraySize())) {
6243 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006244 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006245
6246 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6247 // Note that we only do this for alloca's, because malloc should allocate and
6248 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006249 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006250 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006251 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6252
Chris Lattner1085bdf2002-11-04 16:18:53 +00006253 return 0;
6254}
6255
Chris Lattner8427bff2003-12-07 01:24:23 +00006256Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6257 Value *Op = FI.getOperand(0);
6258
6259 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6260 if (CastInst *CI = dyn_cast<CastInst>(Op))
6261 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6262 FI.setOperand(0, CI->getOperand(0));
6263 return &FI;
6264 }
6265
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006266 // free undef -> unreachable.
6267 if (isa<UndefValue>(Op)) {
6268 // Insert a new store to null because we cannot modify the CFG here.
6269 new StoreInst(ConstantBool::True,
6270 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6271 return EraseInstFromFunction(FI);
6272 }
6273
Chris Lattnerf3a36602004-02-28 04:57:37 +00006274 // If we have 'free null' delete the instruction. This can happen in stl code
6275 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006276 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006277 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006278
Chris Lattner8427bff2003-12-07 01:24:23 +00006279 return 0;
6280}
6281
6282
Chris Lattner72684fe2005-01-31 05:51:45 +00006283/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006284static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6285 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006286 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006287
6288 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006289 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006290 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006291
Chris Lattnerebca4762006-04-02 05:37:12 +00006292 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6293 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006294 // If the source is an array, the code below will not succeed. Check to
6295 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6296 // constants.
6297 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6298 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6299 if (ASrcTy->getNumElements() != 0) {
6300 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6301 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6302 SrcTy = cast<PointerType>(CastOp->getType());
6303 SrcPTy = SrcTy->getElementType();
6304 }
6305
Chris Lattnerebca4762006-04-02 05:37:12 +00006306 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6307 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006308 // Do not allow turning this into a load of an integer, which is then
6309 // casted to a pointer, this pessimizes pointer analysis a lot.
6310 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006311 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006312 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006313
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006314 // Okay, we are casting from one integer or pointer type to another of
6315 // the same size. Instead of casting the pointer before the load, cast
6316 // the result of the loaded value.
6317 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6318 CI->getName(),
6319 LI.isVolatile()),LI);
6320 // Now cast the result of the load.
6321 return new CastInst(NewLoad, LI.getType());
6322 }
Chris Lattner35e24772004-07-13 01:49:43 +00006323 }
6324 }
6325 return 0;
6326}
6327
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006328/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006329/// from this value cannot trap. If it is not obviously safe to load from the
6330/// specified pointer, we do a quick local scan of the basic block containing
6331/// ScanFrom, to determine if the address is already accessed.
6332static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6333 // If it is an alloca or global variable, it is always safe to load from.
6334 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6335
6336 // Otherwise, be a little bit agressive by scanning the local block where we
6337 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006338 // from/to. If so, the previous load or store would have already trapped,
6339 // so there is no harm doing an extra load (also, CSE will later eliminate
6340 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006341 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6342
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006343 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006344 --BBI;
6345
6346 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6347 if (LI->getOperand(0) == V) return true;
6348 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6349 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006350
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006351 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006352 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006353}
6354
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006355Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6356 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006357
Chris Lattnera9d84e32005-05-01 04:24:53 +00006358 // load (cast X) --> cast (load X) iff safe
6359 if (CastInst *CI = dyn_cast<CastInst>(Op))
6360 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6361 return Res;
6362
6363 // None of the following transforms are legal for volatile loads.
6364 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006365
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006366 if (&LI.getParent()->front() != &LI) {
6367 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006368 // If the instruction immediately before this is a store to the same
6369 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006370 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6371 if (SI->getOperand(1) == LI.getOperand(0))
6372 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006373 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6374 if (LIB->getOperand(0) == LI.getOperand(0))
6375 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006376 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006377
6378 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6379 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6380 isa<UndefValue>(GEPI->getOperand(0))) {
6381 // Insert a new store to null instruction before the load to indicate
6382 // that this code is not reachable. We do this instead of inserting
6383 // an unreachable instruction directly because we cannot modify the
6384 // CFG.
6385 new StoreInst(UndefValue::get(LI.getType()),
6386 Constant::getNullValue(Op->getType()), &LI);
6387 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6388 }
6389
Chris Lattner81a7a232004-10-16 18:11:37 +00006390 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006391 // load null/undef -> undef
6392 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006393 // Insert a new store to null instruction before the load to indicate that
6394 // this code is not reachable. We do this instead of inserting an
6395 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006396 new StoreInst(UndefValue::get(LI.getType()),
6397 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006398 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006399 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006400
Chris Lattner81a7a232004-10-16 18:11:37 +00006401 // Instcombine load (constant global) into the value loaded.
6402 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6403 if (GV->isConstant() && !GV->isExternal())
6404 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006405
Chris Lattner81a7a232004-10-16 18:11:37 +00006406 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6407 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6408 if (CE->getOpcode() == Instruction::GetElementPtr) {
6409 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6410 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006411 if (Constant *V =
6412 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006413 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006414 if (CE->getOperand(0)->isNullValue()) {
6415 // Insert a new store to null instruction before the load to indicate
6416 // that this code is not reachable. We do this instead of inserting
6417 // an unreachable instruction directly because we cannot modify the
6418 // CFG.
6419 new StoreInst(UndefValue::get(LI.getType()),
6420 Constant::getNullValue(Op->getType()), &LI);
6421 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6422 }
6423
Chris Lattner81a7a232004-10-16 18:11:37 +00006424 } else if (CE->getOpcode() == Instruction::Cast) {
6425 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6426 return Res;
6427 }
6428 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006429
Chris Lattnera9d84e32005-05-01 04:24:53 +00006430 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006431 // Change select and PHI nodes to select values instead of addresses: this
6432 // helps alias analysis out a lot, allows many others simplifications, and
6433 // exposes redundancy in the code.
6434 //
6435 // Note that we cannot do the transformation unless we know that the
6436 // introduced loads cannot trap! Something like this is valid as long as
6437 // the condition is always false: load (select bool %C, int* null, int* %G),
6438 // but it would not be valid if we transformed it to load from null
6439 // unconditionally.
6440 //
6441 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6442 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006443 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6444 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006445 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006446 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006447 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006448 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006449 return new SelectInst(SI->getCondition(), V1, V2);
6450 }
6451
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006452 // load (select (cond, null, P)) -> load P
6453 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6454 if (C->isNullValue()) {
6455 LI.setOperand(0, SI->getOperand(2));
6456 return &LI;
6457 }
6458
6459 // load (select (cond, P, null)) -> load P
6460 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6461 if (C->isNullValue()) {
6462 LI.setOperand(0, SI->getOperand(1));
6463 return &LI;
6464 }
6465
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006466 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6467 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006468 bool Safe = PN->getParent() == LI.getParent();
6469
6470 // Scan all of the instructions between the PHI and the load to make
6471 // sure there are no instructions that might possibly alter the value
6472 // loaded from the PHI.
6473 if (Safe) {
6474 BasicBlock::iterator I = &LI;
6475 for (--I; !isa<PHINode>(I); --I)
6476 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6477 Safe = false;
6478 break;
6479 }
6480 }
6481
6482 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006483 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006484 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006485 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006486
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006487 if (Safe) {
6488 // Create the PHI.
6489 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6490 InsertNewInstBefore(NewPN, *PN);
6491 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6492
6493 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6494 BasicBlock *BB = PN->getIncomingBlock(i);
6495 Value *&TheLoad = LoadMap[BB];
6496 if (TheLoad == 0) {
6497 Value *InVal = PN->getIncomingValue(i);
6498 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6499 InVal->getName()+".val"),
6500 *BB->getTerminator());
6501 }
6502 NewPN->addIncoming(TheLoad, BB);
6503 }
6504 return ReplaceInstUsesWith(LI, NewPN);
6505 }
6506 }
6507 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006508 return 0;
6509}
6510
Chris Lattner72684fe2005-01-31 05:51:45 +00006511/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6512/// when possible.
6513static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6514 User *CI = cast<User>(SI.getOperand(1));
6515 Value *CastOp = CI->getOperand(0);
6516
6517 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6518 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6519 const Type *SrcPTy = SrcTy->getElementType();
6520
6521 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6522 // If the source is an array, the code below will not succeed. Check to
6523 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6524 // constants.
6525 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6526 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6527 if (ASrcTy->getNumElements() != 0) {
6528 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6529 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6530 SrcTy = cast<PointerType>(CastOp->getType());
6531 SrcPTy = SrcTy->getElementType();
6532 }
6533
6534 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006535 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006536 IC.getTargetData().getTypeSize(DestPTy)) {
6537
6538 // Okay, we are casting from one integer or pointer type to another of
6539 // the same size. Instead of casting the pointer before the store, cast
6540 // the value to be stored.
6541 Value *NewCast;
6542 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6543 NewCast = ConstantExpr::getCast(C, SrcPTy);
6544 else
6545 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6546 SrcPTy,
6547 SI.getOperand(0)->getName()+".c"), SI);
6548
6549 return new StoreInst(NewCast, CastOp);
6550 }
6551 }
6552 }
6553 return 0;
6554}
6555
Chris Lattner31f486c2005-01-31 05:36:43 +00006556Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6557 Value *Val = SI.getOperand(0);
6558 Value *Ptr = SI.getOperand(1);
6559
6560 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006561 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006562 ++NumCombined;
6563 return 0;
6564 }
6565
Chris Lattner5997cf92006-02-08 03:25:32 +00006566 // Do really simple DSE, to catch cases where there are several consequtive
6567 // stores to the same location, separated by a few arithmetic operations. This
6568 // situation often occurs with bitfield accesses.
6569 BasicBlock::iterator BBI = &SI;
6570 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6571 --ScanInsts) {
6572 --BBI;
6573
6574 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6575 // Prev store isn't volatile, and stores to the same location?
6576 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6577 ++NumDeadStore;
6578 ++BBI;
6579 EraseInstFromFunction(*PrevSI);
6580 continue;
6581 }
6582 break;
6583 }
6584
6585 // Don't skip over loads or things that can modify memory.
6586 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6587 break;
6588 }
6589
6590
6591 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006592
6593 // store X, null -> turns into 'unreachable' in SimplifyCFG
6594 if (isa<ConstantPointerNull>(Ptr)) {
6595 if (!isa<UndefValue>(Val)) {
6596 SI.setOperand(0, UndefValue::get(Val->getType()));
6597 if (Instruction *U = dyn_cast<Instruction>(Val))
6598 WorkList.push_back(U); // Dropped a use.
6599 ++NumCombined;
6600 }
6601 return 0; // Do not modify these!
6602 }
6603
6604 // store undef, Ptr -> noop
6605 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006606 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006607 ++NumCombined;
6608 return 0;
6609 }
6610
Chris Lattner72684fe2005-01-31 05:51:45 +00006611 // If the pointer destination is a cast, see if we can fold the cast into the
6612 // source instead.
6613 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6614 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6615 return Res;
6616 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6617 if (CE->getOpcode() == Instruction::Cast)
6618 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6619 return Res;
6620
Chris Lattner219175c2005-09-12 23:23:25 +00006621
6622 // If this store is the last instruction in the basic block, and if the block
6623 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006624 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006625 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6626 if (BI->isUnconditional()) {
6627 // Check to see if the successor block has exactly two incoming edges. If
6628 // so, see if the other predecessor contains a store to the same location.
6629 // if so, insert a PHI node (if needed) and move the stores down.
6630 BasicBlock *Dest = BI->getSuccessor(0);
6631
6632 pred_iterator PI = pred_begin(Dest);
6633 BasicBlock *Other = 0;
6634 if (*PI != BI->getParent())
6635 Other = *PI;
6636 ++PI;
6637 if (PI != pred_end(Dest)) {
6638 if (*PI != BI->getParent())
6639 if (Other)
6640 Other = 0;
6641 else
6642 Other = *PI;
6643 if (++PI != pred_end(Dest))
6644 Other = 0;
6645 }
6646 if (Other) { // If only one other pred...
6647 BBI = Other->getTerminator();
6648 // Make sure this other block ends in an unconditional branch and that
6649 // there is an instruction before the branch.
6650 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6651 BBI != Other->begin()) {
6652 --BBI;
6653 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6654
6655 // If this instruction is a store to the same location.
6656 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6657 // Okay, we know we can perform this transformation. Insert a PHI
6658 // node now if we need it.
6659 Value *MergedVal = OtherStore->getOperand(0);
6660 if (MergedVal != SI.getOperand(0)) {
6661 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6662 PN->reserveOperandSpace(2);
6663 PN->addIncoming(SI.getOperand(0), SI.getParent());
6664 PN->addIncoming(OtherStore->getOperand(0), Other);
6665 MergedVal = InsertNewInstBefore(PN, Dest->front());
6666 }
6667
6668 // Advance to a place where it is safe to insert the new store and
6669 // insert it.
6670 BBI = Dest->begin();
6671 while (isa<PHINode>(BBI)) ++BBI;
6672 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6673 OtherStore->isVolatile()), *BBI);
6674
6675 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006676 EraseInstFromFunction(SI);
6677 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006678 ++NumCombined;
6679 return 0;
6680 }
6681 }
6682 }
6683 }
6684
Chris Lattner31f486c2005-01-31 05:36:43 +00006685 return 0;
6686}
6687
6688
Chris Lattner9eef8a72003-06-04 04:46:00 +00006689Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6690 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006691 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006692 BasicBlock *TrueDest;
6693 BasicBlock *FalseDest;
6694 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6695 !isa<Constant>(X)) {
6696 // Swap Destinations and condition...
6697 BI.setCondition(X);
6698 BI.setSuccessor(0, FalseDest);
6699 BI.setSuccessor(1, TrueDest);
6700 return &BI;
6701 }
6702
6703 // Cannonicalize setne -> seteq
6704 Instruction::BinaryOps Op; Value *Y;
6705 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6706 TrueDest, FalseDest)))
6707 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6708 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6709 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6710 std::string Name = I->getName(); I->setName("");
6711 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6712 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006713 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006714 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006715 BI.setSuccessor(0, FalseDest);
6716 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006717 removeFromWorkList(I);
6718 I->getParent()->getInstList().erase(I);
6719 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006720 return &BI;
6721 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006722
Chris Lattner9eef8a72003-06-04 04:46:00 +00006723 return 0;
6724}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006725
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006726Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6727 Value *Cond = SI.getCondition();
6728 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6729 if (I->getOpcode() == Instruction::Add)
6730 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6731 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6732 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006733 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006734 AddRHS));
6735 SI.setOperand(0, I->getOperand(0));
6736 WorkList.push_back(I);
6737 return &SI;
6738 }
6739 }
6740 return 0;
6741}
6742
Chris Lattner6bc98652006-03-05 00:22:33 +00006743/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6744/// is to leave as a vector operation.
6745static bool CheapToScalarize(Value *V, bool isConstant) {
6746 if (isa<ConstantAggregateZero>(V))
6747 return true;
6748 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6749 if (isConstant) return true;
6750 // If all elts are the same, we can extract.
6751 Constant *Op0 = C->getOperand(0);
6752 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6753 if (C->getOperand(i) != Op0)
6754 return false;
6755 return true;
6756 }
6757 Instruction *I = dyn_cast<Instruction>(V);
6758 if (!I) return false;
6759
6760 // Insert element gets simplified to the inserted element or is deleted if
6761 // this is constant idx extract element and its a constant idx insertelt.
6762 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6763 isa<ConstantInt>(I->getOperand(2)))
6764 return true;
6765 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6766 return true;
6767 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6768 if (BO->hasOneUse() &&
6769 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6770 CheapToScalarize(BO->getOperand(1), isConstant)))
6771 return true;
6772
6773 return false;
6774}
6775
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006776/// FindScalarElement - Given a vector and an element number, see if the scalar
6777/// value is already around as a register, for example if it were inserted then
6778/// extracted from the vector.
6779static Value *FindScalarElement(Value *V, unsigned EltNo) {
6780 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6781 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00006782 unsigned Width = PTy->getNumElements();
6783 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006784 return UndefValue::get(PTy->getElementType());
6785
6786 if (isa<UndefValue>(V))
6787 return UndefValue::get(PTy->getElementType());
6788 else if (isa<ConstantAggregateZero>(V))
6789 return Constant::getNullValue(PTy->getElementType());
6790 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6791 return CP->getOperand(EltNo);
6792 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6793 // If this is an insert to a variable element, we don't know what it is.
6794 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6795 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6796
6797 // If this is an insert to the element we are looking for, return the
6798 // inserted value.
6799 if (EltNo == IIElt) return III->getOperand(1);
6800
6801 // Otherwise, the insertelement doesn't modify the value, recurse on its
6802 // vector input.
6803 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00006804 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
6805 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
6806 return FindScalarElement(SVI->getOperand(0), 0);
6807 } else if (ConstantPacked *CP =
6808 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
6809 if (isa<UndefValue>(CP->getOperand(EltNo)))
6810 return UndefValue::get(PTy->getElementType());
6811 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
6812 if (InEl < Width)
6813 return FindScalarElement(SVI->getOperand(0), InEl);
6814 else
6815 return FindScalarElement(SVI->getOperand(1), InEl - Width);
6816 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006817 }
6818
6819 // Otherwise, we don't know.
6820 return 0;
6821}
6822
Robert Bocchinoa8352962006-01-13 22:48:06 +00006823Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006824
Chris Lattner92346c32006-03-31 18:25:14 +00006825 // If packed val is undef, replace extract with scalar undef.
6826 if (isa<UndefValue>(EI.getOperand(0)))
6827 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6828
6829 // If packed val is constant 0, replace extract with scalar 0.
6830 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6831 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6832
Robert Bocchinoa8352962006-01-13 22:48:06 +00006833 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6834 // If packed val is constant with uniform operands, replace EI
6835 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00006836 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00006837 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00006838 if (C->getOperand(i) != op0) {
6839 op0 = 0;
6840 break;
6841 }
6842 if (op0)
6843 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00006844 }
Chris Lattner6bc98652006-03-05 00:22:33 +00006845
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006846 // If extracting a specified index from the vector, see if we can recursively
6847 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00006848 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006849 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6850 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00006851 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006852
Robert Bocchinoa8352962006-01-13 22:48:06 +00006853 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6854 if (I->hasOneUse()) {
6855 // Push extractelement into predecessor operation if legal and
6856 // profitable to do so
6857 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00006858 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6859 if (CheapToScalarize(BO, isConstantElt)) {
6860 ExtractElementInst *newEI0 =
6861 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6862 EI.getName()+".lhs");
6863 ExtractElementInst *newEI1 =
6864 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6865 EI.getName()+".rhs");
6866 InsertNewInstBefore(newEI0, EI);
6867 InsertNewInstBefore(newEI1, EI);
6868 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6869 }
6870 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00006871 Value *Ptr = InsertCastBefore(I->getOperand(0),
6872 PointerType::get(EI.getType()), EI);
6873 GetElementPtrInst *GEP =
6874 new GetElementPtrInst(Ptr, EI.getOperand(1),
6875 I->getName() + ".gep");
6876 InsertNewInstBefore(GEP, EI);
6877 return new LoadInst(GEP);
Chris Lattner6bc98652006-03-05 00:22:33 +00006878 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6879 // Extracting the inserted element?
6880 if (IE->getOperand(2) == EI.getOperand(1))
6881 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6882 // If the inserted and extracted elements are constants, they must not
Chris Lattner612fa8e2006-03-30 22:02:40 +00006883 // be the same value, extract from the pre-inserted value instead.
6884 if (isa<Constant>(IE->getOperand(2)) &&
6885 isa<Constant>(EI.getOperand(1))) {
6886 AddUsesToWorkList(EI);
6887 EI.setOperand(0, IE->getOperand(0));
6888 return &EI;
6889 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00006890 }
6891 }
6892 return 0;
6893}
6894
Chris Lattnerfbb77a42006-04-10 22:45:52 +00006895Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
6896 Value *LHS = SVI.getOperand(0);
6897 Value *RHS = SVI.getOperand(1);
6898 Constant *Mask = cast<Constant>(SVI.getOperand(2));
6899
6900 bool MadeChange = false;
6901
6902 if (isa<UndefValue>(Mask))
6903 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
6904
6905 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
6906 if (LHS == RHS) {
6907 if (isa<UndefValue>(LHS)) {
6908 // shuffle(undef,undef,mask) -> undef.
6909 return ReplaceInstUsesWith(SVI, LHS);
6910 }
6911
6912 if (!isa<ConstantAggregateZero>(Mask)) {
6913 // Remap any references to RHS to use LHS.
6914 ConstantPacked *CP = cast<ConstantPacked>(Mask);
6915 std::vector<Constant*> Elts;
6916 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
6917 Elts.push_back(CP->getOperand(i));
6918 if (isa<UndefValue>(CP->getOperand(i)))
6919 continue;
6920 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
6921 if (MV >= e)
6922 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
6923 }
6924 Mask = ConstantPacked::get(Elts);
6925 }
6926 SVI.setOperand(1, UndefValue::get(RHS->getType()));
6927 SVI.setOperand(2, Mask);
6928 MadeChange = true;
6929 }
6930
6931 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
6932 bool isLHSID = true, isRHSID = true;
6933
6934 // Analyze the shuffle.
6935 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
6936 if (isa<UndefValue>(CP->getOperand(i)))
6937 continue;
6938 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
6939
6940 // Is this an identity shuffle of the LHS value?
6941 isLHSID &= (MV == i);
6942
6943 // Is this an identity shuffle of the RHS value?
6944 isRHSID &= (MV-e == i);
6945 }
6946
6947 // Eliminate identity shuffles.
6948 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
6949 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
6950 }
6951
6952 return MadeChange ? &SVI : 0;
6953}
6954
6955
Robert Bocchinoa8352962006-01-13 22:48:06 +00006956
Chris Lattner99f48c62002-09-02 04:59:56 +00006957void InstCombiner::removeFromWorkList(Instruction *I) {
6958 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6959 WorkList.end());
6960}
6961
Chris Lattner39c98bb2004-12-08 23:43:58 +00006962
6963/// TryToSinkInstruction - Try to move the specified instruction from its
6964/// current block into the beginning of DestBlock, which can only happen if it's
6965/// safe to move the instruction past all of the instructions between it and the
6966/// end of its block.
6967static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6968 assert(I->hasOneUse() && "Invariants didn't hold!");
6969
Chris Lattnerc4f67e62005-10-27 17:13:11 +00006970 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6971 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006972
Chris Lattner39c98bb2004-12-08 23:43:58 +00006973 // Do not sink alloca instructions out of the entry block.
6974 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6975 return false;
6976
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006977 // We can only sink load instructions if there is nothing between the load and
6978 // the end of block that could change the value.
6979 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006980 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6981 Scan != E; ++Scan)
6982 if (Scan->mayWriteToMemory())
6983 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006984 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00006985
6986 BasicBlock::iterator InsertPos = DestBlock->begin();
6987 while (isa<PHINode>(InsertPos)) ++InsertPos;
6988
Chris Lattner9f269e42005-08-08 19:11:57 +00006989 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00006990 ++NumSunkInst;
6991 return true;
6992}
6993
Chris Lattner113f4f42002-06-25 16:13:24 +00006994bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00006995 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006996 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00006997
Chris Lattner4ed40f72005-07-07 20:40:38 +00006998 {
6999 // Populate the worklist with the reachable instructions.
7000 std::set<BasicBlock*> Visited;
7001 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
7002 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
7003 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
7004 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00007005
Chris Lattner4ed40f72005-07-07 20:40:38 +00007006 // Do a quick scan over the function. If we find any blocks that are
7007 // unreachable, remove any instructions inside of them. This prevents
7008 // the instcombine code from having to deal with some bad special cases.
7009 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7010 if (!Visited.count(BB)) {
7011 Instruction *Term = BB->getTerminator();
7012 while (Term != BB->begin()) { // Remove instrs bottom-up
7013 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00007014
Chris Lattner4ed40f72005-07-07 20:40:38 +00007015 DEBUG(std::cerr << "IC: DCE: " << *I);
7016 ++NumDeadInst;
7017
7018 if (!I->use_empty())
7019 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7020 I->eraseFromParent();
7021 }
7022 }
7023 }
Chris Lattnerca081252001-12-14 16:52:21 +00007024
7025 while (!WorkList.empty()) {
7026 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7027 WorkList.pop_back();
7028
Misha Brukman632df282002-10-29 23:06:16 +00007029 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00007030 // Check to see if we can DIE the instruction...
7031 if (isInstructionTriviallyDead(I)) {
7032 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007033 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00007034 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00007035 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007036
Chris Lattnercd517ff2005-01-28 19:32:01 +00007037 DEBUG(std::cerr << "IC: DCE: " << *I);
7038
7039 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007040 removeFromWorkList(I);
7041 continue;
7042 }
Chris Lattner99f48c62002-09-02 04:59:56 +00007043
Misha Brukman632df282002-10-29 23:06:16 +00007044 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00007045 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007046 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00007047 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007048 cast<Constant>(Ptr)->isNullValue() &&
7049 !isa<ConstantPointerNull>(C) &&
7050 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00007051 // If this is a constant expr gep that is effectively computing an
7052 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
7053 bool isFoldableGEP = true;
7054 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
7055 if (!isa<ConstantInt>(I->getOperand(i)))
7056 isFoldableGEP = false;
7057 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007058 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00007059 std::vector<Value*>(I->op_begin()+1, I->op_end()));
7060 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00007061 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00007062 C = ConstantExpr::getCast(C, I->getType());
7063 }
7064 }
7065
Chris Lattnercd517ff2005-01-28 19:32:01 +00007066 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7067
Chris Lattner99f48c62002-09-02 04:59:56 +00007068 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00007069 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00007070 ReplaceInstUsesWith(*I, C);
7071
Chris Lattner99f48c62002-09-02 04:59:56 +00007072 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007073 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00007074 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007075 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00007076 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007077
Chris Lattner39c98bb2004-12-08 23:43:58 +00007078 // See if we can trivially sink this instruction to a successor basic block.
7079 if (I->hasOneUse()) {
7080 BasicBlock *BB = I->getParent();
7081 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7082 if (UserParent != BB) {
7083 bool UserIsSuccessor = false;
7084 // See if the user is one of our successors.
7085 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7086 if (*SI == UserParent) {
7087 UserIsSuccessor = true;
7088 break;
7089 }
7090
7091 // If the user is one of our immediate successors, and if that successor
7092 // only has us as a predecessors (we'd have to split the critical edge
7093 // otherwise), we can keep going.
7094 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7095 next(pred_begin(UserParent)) == pred_end(UserParent))
7096 // Okay, the CFG is simple enough, try to sink this instruction.
7097 Changed |= TryToSinkInstruction(I, UserParent);
7098 }
7099 }
7100
Chris Lattnerca081252001-12-14 16:52:21 +00007101 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007102 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00007103 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00007104 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00007105 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007106 DEBUG(std::cerr << "IC: Old = " << *I
7107 << " New = " << *Result);
7108
Chris Lattner396dbfe2004-06-09 05:08:07 +00007109 // Everything uses the new instruction now.
7110 I->replaceAllUsesWith(Result);
7111
7112 // Push the new instruction and any users onto the worklist.
7113 WorkList.push_back(Result);
7114 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007115
7116 // Move the name to the new instruction first...
7117 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00007118 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007119
7120 // Insert the new instruction into the basic block...
7121 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00007122 BasicBlock::iterator InsertPos = I;
7123
7124 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7125 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7126 ++InsertPos;
7127
7128 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007129
Chris Lattner63d75af2004-05-01 23:27:23 +00007130 // Make sure that we reprocess all operands now that we reduced their
7131 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00007132 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7133 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7134 WorkList.push_back(OpI);
7135
Chris Lattner396dbfe2004-06-09 05:08:07 +00007136 // Instructions can end up on the worklist more than once. Make sure
7137 // we do not process an instruction that has been deleted.
7138 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007139
7140 // Erase the old instruction.
7141 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00007142 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007143 DEBUG(std::cerr << "IC: MOD = " << *I);
7144
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007145 // If the instruction was modified, it's possible that it is now dead.
7146 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00007147 if (isInstructionTriviallyDead(I)) {
7148 // Make sure we process all operands now that we are reducing their
7149 // use counts.
7150 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7151 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7152 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007153
Chris Lattner63d75af2004-05-01 23:27:23 +00007154 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00007155 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007156 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00007157 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00007158 } else {
7159 WorkList.push_back(Result);
7160 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007161 }
Chris Lattner053c0932002-05-14 15:24:07 +00007162 }
Chris Lattner260ab202002-04-18 17:39:14 +00007163 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00007164 }
7165 }
7166
Chris Lattner260ab202002-04-18 17:39:14 +00007167 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00007168}
7169
Brian Gaeke38b79e82004-07-27 17:43:21 +00007170FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00007171 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00007172}
Brian Gaeke960707c2003-11-11 22:41:34 +00007173