blob: 6491ff9b0f7fdd3f648bd19977dfd3477e475533 [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);
Chris Lattner39fac442006-04-15 01:39:45 +0000140 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000141 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000142 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000143
144 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000145 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000146
Chris Lattner970c33a2003-06-19 17:00:31 +0000147 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000148 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000149 bool transformConstExprCastCall(CallSite CS);
150
Chris Lattner69193f92004-04-05 01:30:19 +0000151 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000152 // InsertNewInstBefore - insert an instruction New before instruction Old
153 // in the program. Add the new instruction to the worklist.
154 //
Chris Lattner623826c2004-09-28 21:48:02 +0000155 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000156 assert(New && New->getParent() == 0 &&
157 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000158 BasicBlock *BB = Old.getParent();
159 BB->getInstList().insert(&Old, New); // Insert inst
160 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000161 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000162 }
163
Chris Lattner7e794272004-09-24 15:21:34 +0000164 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
165 /// This also adds the cast to the worklist. Finally, this returns the
166 /// cast.
167 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
168 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000169
Chris Lattnere79d2492006-04-06 19:19:17 +0000170 if (Constant *CV = dyn_cast<Constant>(V))
171 return ConstantExpr::getCast(CV, Ty);
172
Chris Lattner7e794272004-09-24 15:21:34 +0000173 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
174 WorkList.push_back(C);
175 return C;
176 }
177
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000178 // ReplaceInstUsesWith - This method is to be used when an instruction is
179 // found to be dead, replacable with another preexisting expression. Here
180 // we add all uses of I to the worklist, replace all uses of I with the new
181 // value, then return I, so that the inst combiner will know that I was
182 // modified.
183 //
184 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000185 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000186 if (&I != V) {
187 I.replaceAllUsesWith(V);
188 return &I;
189 } else {
190 // If we are replacing the instruction with itself, this must be in a
191 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000192 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000193 return &I;
194 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000195 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000196
Chris Lattner2590e512006-02-07 06:56:34 +0000197 // UpdateValueUsesWith - This method is to be used when an value is
198 // found to be replacable with another preexisting expression or was
199 // updated. Here we add all uses of I to the worklist, replace all uses of
200 // I with the new value (unless the instruction was just updated), then
201 // return true, so that the inst combiner will know that I was modified.
202 //
203 bool UpdateValueUsesWith(Value *Old, Value *New) {
204 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
205 if (Old != New)
206 Old->replaceAllUsesWith(New);
207 if (Instruction *I = dyn_cast<Instruction>(Old))
208 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000209 if (Instruction *I = dyn_cast<Instruction>(New))
210 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000211 return true;
212 }
213
Chris Lattner51ea1272004-02-28 05:22:00 +0000214 // EraseInstFromFunction - When dealing with an instruction that has side
215 // effects or produces a void value, we can't rely on DCE to delete the
216 // instruction. Instead, visit methods should return the value returned by
217 // this function.
218 Instruction *EraseInstFromFunction(Instruction &I) {
219 assert(I.use_empty() && "Cannot erase instruction that is used!");
220 AddUsesToWorkList(I);
221 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000222 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000223 return 0; // Don't do anything with FI
224 }
225
Chris Lattner3ac7c262003-08-13 20:16:26 +0000226 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000227 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
228 /// InsertBefore instruction. This is specialized a bit to avoid inserting
229 /// casts that are known to not do anything...
230 ///
231 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
232 Instruction *InsertBefore);
233
Chris Lattner7fb29e12003-03-11 00:12:48 +0000234 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000235 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000237
Chris Lattner0157e7f2006-02-11 09:31:47 +0000238 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
239 uint64_t &KnownZero, uint64_t &KnownOne,
240 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000241
242 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
243 // PHI node as operand #0, see if we can fold the instruction into the PHI
244 // (which is only possible if all operands to the PHI are constants).
245 Instruction *FoldOpIntoPhi(Instruction &I);
246
Chris Lattner7515cab2004-11-14 19:13:23 +0000247 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
248 // operator and they all are only used by the PHI, PHI together their
249 // inputs, and do the operation once, to the result of the PHI.
250 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
251
Chris Lattnerba1cb382003-09-19 17:17:26 +0000252 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
253 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000254
255 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
256 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000257 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
258 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000259 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000260 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000261
Chris Lattnerc8b70922002-07-26 21:12:46 +0000262 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000263}
264
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000265// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000266// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267static unsigned getComplexity(Value *V) {
268 if (isa<Instruction>(V)) {
269 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000270 return 3;
271 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000273 if (isa<Argument>(V)) return 3;
274 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000275}
Chris Lattner260ab202002-04-18 17:39:14 +0000276
Chris Lattner7fb29e12003-03-11 00:12:48 +0000277// isOnlyUse - Return true if this instruction will be deleted if we stop using
278// it.
279static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000280 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000281}
282
Chris Lattnere79e8542004-02-23 06:38:22 +0000283// getPromotedType - Return the specified type promoted as it would be to pass
284// though a va_arg area...
285static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000286 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000287 case Type::SByteTyID:
288 case Type::ShortTyID: return Type::IntTy;
289 case Type::UByteTyID:
290 case Type::UShortTyID: return Type::UIntTy;
291 case Type::FloatTyID: return Type::DoubleTy;
292 default: return Ty;
293 }
294}
295
Chris Lattner567b81f2005-09-13 00:40:14 +0000296/// isCast - If the specified operand is a CastInst or a constant expr cast,
297/// return the operand value, otherwise return null.
298static Value *isCast(Value *V) {
299 if (CastInst *I = dyn_cast<CastInst>(V))
300 return I->getOperand(0);
301 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
302 if (CE->getOpcode() == Instruction::Cast)
303 return CE->getOperand(0);
304 return 0;
305}
306
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000307// SimplifyCommutative - This performs a few simplifications for commutative
308// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000309//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000310// 1. Order operands such that they are listed from right (least complex) to
311// left (most complex). This puts constants before unary operators before
312// binary operators.
313//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
315// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000316//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000318 bool Changed = false;
319 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
320 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000321
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000322 if (!I.isAssociative()) return Changed;
323 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000324 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
325 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
326 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000327 Constant *Folded = ConstantExpr::get(I.getOpcode(),
328 cast<Constant>(I.getOperand(1)),
329 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000330 I.setOperand(0, Op->getOperand(0));
331 I.setOperand(1, Folded);
332 return true;
333 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
334 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
335 isOnlyUse(Op) && isOnlyUse(Op1)) {
336 Constant *C1 = cast<Constant>(Op->getOperand(1));
337 Constant *C2 = cast<Constant>(Op1->getOperand(1));
338
339 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000340 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000341 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
342 Op1->getOperand(0),
343 Op1->getName(), &I);
344 WorkList.push_back(New);
345 I.setOperand(0, New);
346 I.setOperand(1, Folded);
347 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000348 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000349 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000350 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000351}
Chris Lattnerca081252001-12-14 16:52:21 +0000352
Chris Lattnerbb74e222003-03-10 23:06:50 +0000353// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
354// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000355//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000356static inline Value *dyn_castNegVal(Value *V) {
357 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000358 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000359
Chris Lattner9ad0d552004-12-14 20:08:06 +0000360 // Constants can be considered to be negated values if they can be folded.
361 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
362 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000363 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000364}
365
Chris Lattnerbb74e222003-03-10 23:06:50 +0000366static inline Value *dyn_castNotVal(Value *V) {
367 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000368 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000369
370 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000371 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000372 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000373 return 0;
374}
375
Chris Lattner7fb29e12003-03-11 00:12:48 +0000376// dyn_castFoldableMul - If this value is a multiply that can be folded into
377// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000378// non-constant operand of the multiply, and set CST to point to the multiplier.
379// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000380//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000381static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000382 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000383 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000384 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000385 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000386 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000387 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000388 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000389 // The multiplier is really 1 << CST.
390 Constant *One = ConstantInt::get(V->getType(), 1);
391 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
392 return I->getOperand(0);
393 }
394 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000395 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000396}
Chris Lattner31ae8632002-08-14 17:51:49 +0000397
Chris Lattner0798af32005-01-13 20:14:25 +0000398/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
399/// expression, return it.
400static User *dyn_castGetElementPtr(Value *V) {
401 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
403 if (CE->getOpcode() == Instruction::GetElementPtr)
404 return cast<User>(V);
405 return false;
406}
407
Chris Lattner623826c2004-09-28 21:48:02 +0000408// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000409static ConstantInt *AddOne(ConstantInt *C) {
410 return cast<ConstantInt>(ConstantExpr::getAdd(C,
411 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000412}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000413static ConstantInt *SubOne(ConstantInt *C) {
414 return cast<ConstantInt>(ConstantExpr::getSub(C,
415 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000416}
417
Chris Lattner0157e7f2006-02-11 09:31:47 +0000418/// GetConstantInType - Return a ConstantInt with the specified type and value.
419///
Chris Lattneree0f2802006-02-12 02:07:56 +0000420static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000421 if (Ty->isUnsigned())
422 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000423 else if (Ty->getTypeID() == Type::BoolTyID)
424 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000425 int64_t SVal = Val;
426 SVal <<= 64-Ty->getPrimitiveSizeInBits();
427 SVal >>= 64-Ty->getPrimitiveSizeInBits();
428 return ConstantSInt::get(Ty, SVal);
429}
430
431
Chris Lattner4534dd592006-02-09 07:38:58 +0000432/// ComputeMaskedBits - Determine which of the bits specified in Mask are
433/// known to be either zero or one and return them in the KnownZero/KnownOne
434/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
435/// processing.
436static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
437 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000438 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
439 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000440 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000441 // optimized based on the contradictory assumption that it is non-zero.
442 // Because instcombine aggressively folds operations with undef args anyway,
443 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000444 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
445 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000446 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000447 KnownZero = ~KnownOne & Mask;
448 return;
449 }
450
451 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000452 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000453 return; // Limit search depth.
454
455 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000456 Instruction *I = dyn_cast<Instruction>(V);
457 if (!I) return;
458
Chris Lattnerfb296922006-05-04 17:33:35 +0000459 Mask &= V->getType()->getIntegralTypeMask();
460
Chris Lattner0157e7f2006-02-11 09:31:47 +0000461 switch (I->getOpcode()) {
462 case Instruction::And:
463 // If either the LHS or the RHS are Zero, the result is zero.
464 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
465 Mask &= ~KnownZero;
466 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
467 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
468 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
469
470 // Output known-1 bits are only known if set in both the LHS & RHS.
471 KnownOne &= KnownOne2;
472 // Output known-0 are known to be clear if zero in either the LHS | RHS.
473 KnownZero |= KnownZero2;
474 return;
475 case Instruction::Or:
476 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
477 Mask &= ~KnownOne;
478 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
479 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
480 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
481
482 // Output known-0 bits are only known if clear in both the LHS & RHS.
483 KnownZero &= KnownZero2;
484 // Output known-1 are known to be set if set in either the LHS | RHS.
485 KnownOne |= KnownOne2;
486 return;
487 case Instruction::Xor: {
488 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
489 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
490 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
491 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
492
493 // Output known-0 bits are known if clear or set in both the LHS & RHS.
494 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
495 // Output known-1 are known to be set if set in only one of the LHS, RHS.
496 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
497 KnownZero = KnownZeroOut;
498 return;
499 }
500 case Instruction::Select:
501 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
502 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
503 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
504 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
505
506 // Only known if known in both the LHS and RHS.
507 KnownOne &= KnownOne2;
508 KnownZero &= KnownZero2;
509 return;
510 case Instruction::Cast: {
511 const Type *SrcTy = I->getOperand(0)->getType();
512 if (!SrcTy->isIntegral()) return;
513
514 // If this is an integer truncate or noop, just look in the input.
515 if (SrcTy->getPrimitiveSizeInBits() >=
516 I->getType()->getPrimitiveSizeInBits()) {
517 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000518 return;
519 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000520
Chris Lattner0157e7f2006-02-11 09:31:47 +0000521 // Sign or Zero extension. Compute the bits in the result that are not
522 // present in the input.
523 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
524 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000525
Chris Lattner0157e7f2006-02-11 09:31:47 +0000526 // Handle zero extension.
527 if (!SrcTy->isSigned()) {
528 Mask &= SrcTy->getIntegralTypeMask();
529 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
530 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
531 // The top bits are known to be zero.
532 KnownZero |= NewBits;
533 } else {
534 // Sign extension.
535 Mask &= SrcTy->getIntegralTypeMask();
536 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
537 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000538
Chris Lattner0157e7f2006-02-11 09:31:47 +0000539 // If the sign bit of the input is known set or clear, then we know the
540 // top bits of the result.
541 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
542 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000543 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000544 KnownOne &= ~NewBits;
545 } else if (KnownOne & InSignBit) { // Input sign bit known set
546 KnownOne |= NewBits;
547 KnownZero &= ~NewBits;
548 } else { // Input sign bit unknown
549 KnownZero &= ~NewBits;
550 KnownOne &= ~NewBits;
551 }
552 }
553 return;
554 }
555 case Instruction::Shl:
556 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
557 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
558 Mask >>= SA->getValue();
559 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
560 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
561 KnownZero <<= SA->getValue();
562 KnownOne <<= SA->getValue();
563 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
564 return;
565 }
566 break;
567 case Instruction::Shr:
568 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
569 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
570 // Compute the new bits that are at the top now.
571 uint64_t HighBits = (1ULL << SA->getValue())-1;
572 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
573
574 if (I->getType()->isUnsigned()) { // Unsigned shift right.
575 Mask <<= SA->getValue();
576 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
577 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
578 KnownZero >>= SA->getValue();
579 KnownOne >>= SA->getValue();
580 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000581 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000582 Mask <<= SA->getValue();
583 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
584 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
585 KnownZero >>= SA->getValue();
586 KnownOne >>= SA->getValue();
587
588 // Handle the sign bits.
589 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
590 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
591
592 if (KnownZero & SignBit) { // New bits are known zero.
593 KnownZero |= HighBits;
594 } else if (KnownOne & SignBit) { // New bits are known one.
595 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000596 }
597 }
598 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000599 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000600 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000601 }
Chris Lattner92a68652006-02-07 08:05:22 +0000602}
603
604/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
605/// this predicate to simplify operations downstream. Mask is known to be zero
606/// for bits that V cannot have.
607static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000608 uint64_t KnownZero, KnownOne;
609 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
610 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
611 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000612}
613
Chris Lattner0157e7f2006-02-11 09:31:47 +0000614/// ShrinkDemandedConstant - Check to see if the specified operand of the
615/// specified instruction is a constant integer. If so, check to see if there
616/// are any bits set in the constant that are not demanded. If so, shrink the
617/// constant and return true.
618static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
619 uint64_t Demanded) {
620 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
621 if (!OpC) return false;
622
623 // If there are no bits set that aren't demanded, nothing to do.
624 if ((~Demanded & OpC->getZExtValue()) == 0)
625 return false;
626
627 // This is producing any bits that are not needed, shrink the RHS.
628 uint64_t Val = Demanded & OpC->getZExtValue();
629 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
630 return true;
631}
632
Chris Lattneree0f2802006-02-12 02:07:56 +0000633// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
634// set of known zero and one bits, compute the maximum and minimum values that
635// could have the specified known zero and known one bits, returning them in
636// min/max.
637static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
638 uint64_t KnownZero,
639 uint64_t KnownOne,
640 int64_t &Min, int64_t &Max) {
641 uint64_t TypeBits = Ty->getIntegralTypeMask();
642 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
643
644 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
645
646 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
647 // bit if it is unknown.
648 Min = KnownOne;
649 Max = KnownOne|UnknownBits;
650
651 if (SignBit & UnknownBits) { // Sign bit is unknown
652 Min |= SignBit;
653 Max &= ~SignBit;
654 }
655
656 // Sign extend the min/max values.
657 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
658 Min = (Min << ShAmt) >> ShAmt;
659 Max = (Max << ShAmt) >> ShAmt;
660}
661
662// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
663// a set of known zero and one bits, compute the maximum and minimum values that
664// could have the specified known zero and known one bits, returning them in
665// min/max.
666static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
667 uint64_t KnownZero,
668 uint64_t KnownOne,
669 uint64_t &Min,
670 uint64_t &Max) {
671 uint64_t TypeBits = Ty->getIntegralTypeMask();
672 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
673
674 // The minimum value is when the unknown bits are all zeros.
675 Min = KnownOne;
676 // The maximum value is when the unknown bits are all ones.
677 Max = KnownOne|UnknownBits;
678}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000679
680
681/// SimplifyDemandedBits - Look at V. At this point, we know that only the
682/// DemandedMask bits of the result of V are ever used downstream. If we can
683/// use this information to simplify V, do so and return true. Otherwise,
684/// analyze the expression and return a mask of KnownOne and KnownZero bits for
685/// the expression (used to simplify the caller). The KnownZero/One bits may
686/// only be accurate for those bits in the DemandedMask.
687bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
688 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000689 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000690 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
691 // We know all of the bits for a constant!
692 KnownOne = CI->getZExtValue() & DemandedMask;
693 KnownZero = ~KnownOne & DemandedMask;
694 return false;
695 }
696
697 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000698 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000699 if (Depth != 0) { // Not at the root.
700 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
701 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000702 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000703 }
Chris Lattner2590e512006-02-07 06:56:34 +0000704 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000705 // just set the DemandedMask to all bits.
706 DemandedMask = V->getType()->getIntegralTypeMask();
707 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000708 if (V != UndefValue::get(V->getType()))
709 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
710 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000711 } else if (Depth == 6) { // Limit search depth.
712 return false;
713 }
714
715 Instruction *I = dyn_cast<Instruction>(V);
716 if (!I) return false; // Only analyze instructions.
717
Chris Lattnerfb296922006-05-04 17:33:35 +0000718 DemandedMask &= V->getType()->getIntegralTypeMask();
719
Chris Lattner0157e7f2006-02-11 09:31:47 +0000720 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000721 switch (I->getOpcode()) {
722 default: break;
723 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000724 // If either the LHS or the RHS are Zero, the result is zero.
725 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
726 KnownZero, KnownOne, Depth+1))
727 return true;
728 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
729
730 // If something is known zero on the RHS, the bits aren't demanded on the
731 // LHS.
732 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
733 KnownZero2, KnownOne2, Depth+1))
734 return true;
735 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
736
737 // If all of the demanded bits are known one on one side, return the other.
738 // These bits cannot contribute to the result of the 'and'.
739 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
740 return UpdateValueUsesWith(I, I->getOperand(0));
741 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
742 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000743
744 // If all of the demanded bits in the inputs are known zeros, return zero.
745 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
746 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
747
Chris Lattner0157e7f2006-02-11 09:31:47 +0000748 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000749 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000750 return UpdateValueUsesWith(I, I);
751
752 // Output known-1 bits are only known if set in both the LHS & RHS.
753 KnownOne &= KnownOne2;
754 // Output known-0 are known to be clear if zero in either the LHS | RHS.
755 KnownZero |= KnownZero2;
756 break;
757 case Instruction::Or:
758 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
759 KnownZero, KnownOne, Depth+1))
760 return true;
761 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
762 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
763 KnownZero2, KnownOne2, Depth+1))
764 return true;
765 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
766
767 // If all of the demanded bits are known zero on one side, return the other.
768 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000769 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000770 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000771 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000772 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000773
774 // If all of the potentially set bits on one side are known to be set on
775 // the other side, just use the 'other' side.
776 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
777 (DemandedMask & (~KnownZero)))
778 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000779 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
780 (DemandedMask & (~KnownZero2)))
781 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000782
783 // If the RHS is a constant, see if we can simplify it.
784 if (ShrinkDemandedConstant(I, 1, DemandedMask))
785 return UpdateValueUsesWith(I, I);
786
787 // Output known-0 bits are only known if clear in both the LHS & RHS.
788 KnownZero &= KnownZero2;
789 // Output known-1 are known to be set if set in either the LHS | RHS.
790 KnownOne |= KnownOne2;
791 break;
792 case Instruction::Xor: {
793 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
794 KnownZero, KnownOne, Depth+1))
795 return true;
796 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
797 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
798 KnownZero2, KnownOne2, Depth+1))
799 return true;
800 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
801
802 // If all of the demanded bits are known zero on one side, return the other.
803 // These bits cannot contribute to the result of the 'xor'.
804 if ((DemandedMask & KnownZero) == DemandedMask)
805 return UpdateValueUsesWith(I, I->getOperand(0));
806 if ((DemandedMask & KnownZero2) == DemandedMask)
807 return UpdateValueUsesWith(I, I->getOperand(1));
808
809 // Output known-0 bits are known if clear or set in both the LHS & RHS.
810 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
811 // Output known-1 are known to be set if set in only one of the LHS, RHS.
812 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
813
814 // If all of the unknown bits are known to be zero on one side or the other
815 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000816 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000817 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
818 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
819 Instruction *Or =
820 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
821 I->getName());
822 InsertNewInstBefore(Or, *I);
823 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000824 }
825 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000826
Chris Lattner5b2edb12006-02-12 08:02:11 +0000827 // If all of the demanded bits on one side are known, and all of the set
828 // bits on that side are also known to be set on the other side, turn this
829 // into an AND, as we know the bits will be cleared.
830 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
831 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
832 if ((KnownOne & KnownOne2) == KnownOne) {
833 Constant *AndC = GetConstantInType(I->getType(),
834 ~KnownOne & DemandedMask);
835 Instruction *And =
836 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
837 InsertNewInstBefore(And, *I);
838 return UpdateValueUsesWith(I, And);
839 }
840 }
841
Chris Lattner0157e7f2006-02-11 09:31:47 +0000842 // If the RHS is a constant, see if we can simplify it.
843 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
844 if (ShrinkDemandedConstant(I, 1, DemandedMask))
845 return UpdateValueUsesWith(I, I);
846
847 KnownZero = KnownZeroOut;
848 KnownOne = KnownOneOut;
849 break;
850 }
851 case Instruction::Select:
852 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
853 KnownZero, KnownOne, Depth+1))
854 return true;
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 KnownZero2, KnownOne2, Depth+1))
857 return true;
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
860
861 // If the operands are constants, see if we can simplify them.
862 if (ShrinkDemandedConstant(I, 1, DemandedMask))
863 return UpdateValueUsesWith(I, I);
864 if (ShrinkDemandedConstant(I, 2, DemandedMask))
865 return UpdateValueUsesWith(I, I);
866
867 // Only known if known in both the LHS and RHS.
868 KnownOne &= KnownOne2;
869 KnownZero &= KnownZero2;
870 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000871 case Instruction::Cast: {
872 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000873 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000874
Chris Lattner0157e7f2006-02-11 09:31:47 +0000875 // If this is an integer truncate or noop, just look in the input.
876 if (SrcTy->getPrimitiveSizeInBits() >=
877 I->getType()->getPrimitiveSizeInBits()) {
878 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
879 KnownZero, KnownOne, Depth+1))
880 return true;
881 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
882 break;
883 }
884
885 // Sign or Zero extension. Compute the bits in the result that are not
886 // present in the input.
887 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
888 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
889
890 // Handle zero extension.
891 if (!SrcTy->isSigned()) {
892 DemandedMask &= SrcTy->getIntegralTypeMask();
893 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
894 KnownZero, KnownOne, Depth+1))
895 return true;
896 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
897 // The top bits are known to be zero.
898 KnownZero |= NewBits;
899 } else {
900 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +0000901 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
902 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
903
904 // If any of the sign extended bits are demanded, we know that the sign
905 // bit is demanded.
906 if (NewBits & DemandedMask)
907 InputDemandedBits |= InSignBit;
908
909 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000910 KnownZero, KnownOne, Depth+1))
911 return true;
912 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
913
914 // If the sign bit of the input is known set or clear, then we know the
915 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +0000916
Chris Lattner0157e7f2006-02-11 09:31:47 +0000917 // If the input sign bit is known zero, or if the NewBits are not demanded
918 // convert this into a zero extension.
919 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +0000920 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000921 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000922 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000923 I->getOperand(0)->getName());
924 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000925 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +0000926 NewVal = new CastInst(NewVal, I->getType(), I->getName());
927 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000928 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000929 } else if (KnownOne & InSignBit) { // Input sign bit known set
930 KnownOne |= NewBits;
931 KnownZero &= ~NewBits;
932 } else { // Input sign bit unknown
933 KnownZero &= ~NewBits;
934 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +0000935 }
Chris Lattner2590e512006-02-07 06:56:34 +0000936 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000937 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000938 }
Chris Lattner2590e512006-02-07 06:56:34 +0000939 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000940 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
941 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
942 KnownZero, KnownOne, Depth+1))
943 return true;
944 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
945 KnownZero <<= SA->getValue();
946 KnownOne <<= SA->getValue();
947 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
948 }
Chris Lattner2590e512006-02-07 06:56:34 +0000949 break;
950 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000951 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
952 unsigned ShAmt = SA->getValue();
953
954 // Compute the new bits that are at the top now.
955 uint64_t HighBits = (1ULL << ShAmt)-1;
956 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +0000957 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000958 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000959 if (SimplifyDemandedBits(I->getOperand(0),
960 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000961 KnownZero, KnownOne, Depth+1))
962 return true;
963 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000964 KnownZero &= TypeMask;
965 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000966 KnownZero >>= ShAmt;
967 KnownOne >>= ShAmt;
968 KnownZero |= HighBits; // high bits known zero.
969 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000970 if (SimplifyDemandedBits(I->getOperand(0),
971 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000972 KnownZero, KnownOne, Depth+1))
973 return true;
974 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000975 KnownZero &= TypeMask;
976 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000977 KnownZero >>= SA->getValue();
978 KnownOne >>= SA->getValue();
979
980 // Handle the sign bits.
981 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
982 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
983
984 // If the input sign bit is known to be zero, or if none of the top bits
985 // are demanded, turn this into an unsigned shift right.
986 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
987 // Convert the input to unsigned.
988 Instruction *NewVal;
989 NewVal = new CastInst(I->getOperand(0),
990 I->getType()->getUnsignedVersion(),
991 I->getOperand(0)->getName());
992 InsertNewInstBefore(NewVal, *I);
993 // Perform the unsigned shift right.
994 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
995 InsertNewInstBefore(NewVal, *I);
996 // Then cast that to the destination type.
997 NewVal = new CastInst(NewVal, I->getType(), I->getName());
998 InsertNewInstBefore(NewVal, *I);
999 return UpdateValueUsesWith(I, NewVal);
1000 } else if (KnownOne & SignBit) { // New bits are known one.
1001 KnownOne |= HighBits;
1002 }
Chris Lattner2590e512006-02-07 06:56:34 +00001003 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001004 }
Chris Lattner2590e512006-02-07 06:56:34 +00001005 break;
1006 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001007
1008 // If the client is only demanding bits that we know, return the known
1009 // constant.
1010 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1011 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001012 return false;
1013}
1014
Chris Lattner623826c2004-09-28 21:48:02 +00001015// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1016// true when both operands are equal...
1017//
1018static bool isTrueWhenEqual(Instruction &I) {
1019 return I.getOpcode() == Instruction::SetEQ ||
1020 I.getOpcode() == Instruction::SetGE ||
1021 I.getOpcode() == Instruction::SetLE;
1022}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001023
1024/// AssociativeOpt - Perform an optimization on an associative operator. This
1025/// function is designed to check a chain of associative operators for a
1026/// potential to apply a certain optimization. Since the optimization may be
1027/// applicable if the expression was reassociated, this checks the chain, then
1028/// reassociates the expression as necessary to expose the optimization
1029/// opportunity. This makes use of a special Functor, which must define
1030/// 'shouldApply' and 'apply' methods.
1031///
1032template<typename Functor>
1033Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1034 unsigned Opcode = Root.getOpcode();
1035 Value *LHS = Root.getOperand(0);
1036
1037 // Quick check, see if the immediate LHS matches...
1038 if (F.shouldApply(LHS))
1039 return F.apply(Root);
1040
1041 // Otherwise, if the LHS is not of the same opcode as the root, return.
1042 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001043 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001044 // Should we apply this transform to the RHS?
1045 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1046
1047 // If not to the RHS, check to see if we should apply to the LHS...
1048 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1049 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1050 ShouldApply = true;
1051 }
1052
1053 // If the functor wants to apply the optimization to the RHS of LHSI,
1054 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1055 if (ShouldApply) {
1056 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001057
Chris Lattnerb8b97502003-08-13 19:01:45 +00001058 // Now all of the instructions are in the current basic block, go ahead
1059 // and perform the reassociation.
1060 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1061
1062 // First move the selected RHS to the LHS of the root...
1063 Root.setOperand(0, LHSI->getOperand(1));
1064
1065 // Make what used to be the LHS of the root be the user of the root...
1066 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001067 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001068 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1069 return 0;
1070 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001071 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001072 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001073 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1074 BasicBlock::iterator ARI = &Root; ++ARI;
1075 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1076 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001077
1078 // Now propagate the ExtraOperand down the chain of instructions until we
1079 // get to LHSI.
1080 while (TmpLHSI != LHSI) {
1081 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001082 // Move the instruction to immediately before the chain we are
1083 // constructing to avoid breaking dominance properties.
1084 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1085 BB->getInstList().insert(ARI, NextLHSI);
1086 ARI = NextLHSI;
1087
Chris Lattnerb8b97502003-08-13 19:01:45 +00001088 Value *NextOp = NextLHSI->getOperand(1);
1089 NextLHSI->setOperand(1, ExtraOperand);
1090 TmpLHSI = NextLHSI;
1091 ExtraOperand = NextOp;
1092 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001093
Chris Lattnerb8b97502003-08-13 19:01:45 +00001094 // Now that the instructions are reassociated, have the functor perform
1095 // the transformation...
1096 return F.apply(Root);
1097 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001098
Chris Lattnerb8b97502003-08-13 19:01:45 +00001099 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1100 }
1101 return 0;
1102}
1103
1104
1105// AddRHS - Implements: X + X --> X << 1
1106struct AddRHS {
1107 Value *RHS;
1108 AddRHS(Value *rhs) : RHS(rhs) {}
1109 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1110 Instruction *apply(BinaryOperator &Add) const {
1111 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1112 ConstantInt::get(Type::UByteTy, 1));
1113 }
1114};
1115
1116// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1117// iff C1&C2 == 0
1118struct AddMaskingAnd {
1119 Constant *C2;
1120 AddMaskingAnd(Constant *c) : C2(c) {}
1121 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001122 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001123 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001124 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001125 }
1126 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001127 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001128 }
1129};
1130
Chris Lattner86102b82005-01-01 16:22:27 +00001131static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001132 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001133 if (isa<CastInst>(I)) {
1134 if (Constant *SOC = dyn_cast<Constant>(SO))
1135 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001136
Chris Lattner86102b82005-01-01 16:22:27 +00001137 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1138 SO->getName() + ".cast"), I);
1139 }
1140
Chris Lattner183b3362004-04-09 19:05:30 +00001141 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001142 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1143 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001144
Chris Lattner183b3362004-04-09 19:05:30 +00001145 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1146 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001147 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1148 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001149 }
1150
1151 Value *Op0 = SO, *Op1 = ConstOperand;
1152 if (!ConstIsRHS)
1153 std::swap(Op0, Op1);
1154 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001155 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1156 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1157 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1158 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001159 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001160 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001161 abort();
1162 }
Chris Lattner86102b82005-01-01 16:22:27 +00001163 return IC->InsertNewInstBefore(New, I);
1164}
1165
1166// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1167// constant as the other operand, try to fold the binary operator into the
1168// select arguments. This also works for Cast instructions, which obviously do
1169// not have a second operand.
1170static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1171 InstCombiner *IC) {
1172 // Don't modify shared select instructions
1173 if (!SI->hasOneUse()) return 0;
1174 Value *TV = SI->getOperand(1);
1175 Value *FV = SI->getOperand(2);
1176
1177 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001178 // Bool selects with constant operands can be folded to logical ops.
1179 if (SI->getType() == Type::BoolTy) return 0;
1180
Chris Lattner86102b82005-01-01 16:22:27 +00001181 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1182 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1183
1184 return new SelectInst(SI->getCondition(), SelectTrueVal,
1185 SelectFalseVal);
1186 }
1187 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001188}
1189
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001190
1191/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1192/// node as operand #0, see if we can fold the instruction into the PHI (which
1193/// is only possible if all operands to the PHI are constants).
1194Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1195 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001196 unsigned NumPHIValues = PN->getNumIncomingValues();
1197 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1198 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001199
1200 // Check to see if all of the operands of the PHI are constants. If not, we
1201 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001202 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001203 if (!isa<Constant>(PN->getIncomingValue(i)))
1204 return 0;
1205
1206 // Okay, we can do the transformation: create the new PHI node.
1207 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1208 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001209 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001210 InsertNewInstBefore(NewPN, *PN);
1211
1212 // Next, add all of the operands to the PHI.
1213 if (I.getNumOperands() == 2) {
1214 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001215 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001216 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1217 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1218 PN->getIncomingBlock(i));
1219 }
1220 } else {
1221 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1222 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001223 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001224 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1225 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1226 PN->getIncomingBlock(i));
1227 }
1228 }
1229 return ReplaceInstUsesWith(I, NewPN);
1230}
1231
Chris Lattner113f4f42002-06-25 16:13:24 +00001232Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001233 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001234 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001235
Chris Lattnercf4a9962004-04-10 22:01:55 +00001236 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001237 // X + undef -> undef
1238 if (isa<UndefValue>(RHS))
1239 return ReplaceInstUsesWith(I, RHS);
1240
Chris Lattnercf4a9962004-04-10 22:01:55 +00001241 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001242 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1243 if (RHSC->isNullValue())
1244 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001245 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1246 if (CFP->isExactlyValue(-0.0))
1247 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001248 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001249
Chris Lattnercf4a9962004-04-10 22:01:55 +00001250 // X + (signbit) --> X ^ signbit
1251 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001252 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001253 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001254 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001255 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001256
1257 if (isa<PHINode>(LHS))
1258 if (Instruction *NV = FoldOpIntoPhi(I))
1259 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001260
Chris Lattner330628a2006-01-06 17:59:59 +00001261 ConstantInt *XorRHS = 0;
1262 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001263 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1264 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1265 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1266 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1267
1268 uint64_t C0080Val = 1ULL << 31;
1269 int64_t CFF80Val = -C0080Val;
1270 unsigned Size = 32;
1271 do {
1272 if (TySizeBits > Size) {
1273 bool Found = false;
1274 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1275 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1276 if (RHSSExt == CFF80Val) {
1277 if (XorRHS->getZExtValue() == C0080Val)
1278 Found = true;
1279 } else if (RHSZExt == C0080Val) {
1280 if (XorRHS->getSExtValue() == CFF80Val)
1281 Found = true;
1282 }
1283 if (Found) {
1284 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001285 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001286 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001287 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001288 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001289 Size = 0; // Not a sign ext, but can't be any others either.
1290 goto FoundSExt;
1291 }
1292 }
1293 Size >>= 1;
1294 C0080Val >>= Size;
1295 CFF80Val >>= Size;
1296 } while (Size >= 8);
1297
1298FoundSExt:
1299 const Type *MiddleType = 0;
1300 switch (Size) {
1301 default: break;
1302 case 32: MiddleType = Type::IntTy; break;
1303 case 16: MiddleType = Type::ShortTy; break;
1304 case 8: MiddleType = Type::SByteTy; break;
1305 }
1306 if (MiddleType) {
1307 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1308 InsertNewInstBefore(NewTrunc, I);
1309 return new CastInst(NewTrunc, I.getType());
1310 }
1311 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001312 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001313
Chris Lattnerb8b97502003-08-13 19:01:45 +00001314 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001315 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001316 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001317
1318 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1319 if (RHSI->getOpcode() == Instruction::Sub)
1320 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1321 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1322 }
1323 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1324 if (LHSI->getOpcode() == Instruction::Sub)
1325 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1326 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1327 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001328 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001329
Chris Lattner147e9752002-05-08 22:46:53 +00001330 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001331 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001332 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001333
1334 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001335 if (!isa<Constant>(RHS))
1336 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001337 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001338
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001340 ConstantInt *C2;
1341 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1342 if (X == RHS) // X*C + X --> X * (C+1)
1343 return BinaryOperator::createMul(RHS, AddOne(C2));
1344
1345 // X*C1 + X*C2 --> X * (C1+C2)
1346 ConstantInt *C1;
1347 if (X == dyn_castFoldableMul(RHS, C1))
1348 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001349 }
1350
1351 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001352 if (dyn_castFoldableMul(RHS, C2) == LHS)
1353 return BinaryOperator::createMul(LHS, AddOne(C2));
1354
Chris Lattner57c8d992003-02-18 19:57:07 +00001355
Chris Lattnerb8b97502003-08-13 19:01:45 +00001356 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001357 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001358 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001359
Chris Lattnerb9cde762003-10-02 15:11:26 +00001360 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001361 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001362 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1363 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1364 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001365 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001366
Chris Lattnerbff91d92004-10-08 05:07:56 +00001367 // (X & FF00) + xx00 -> (X+xx00) & FF00
1368 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1369 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1370 if (Anded == CRHS) {
1371 // See if all bits from the first bit set in the Add RHS up are included
1372 // in the mask. First, get the rightmost bit.
1373 uint64_t AddRHSV = CRHS->getRawValue();
1374
1375 // Form a mask of all bits from the lowest bit added through the top.
1376 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001377 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001378
1379 // See if the and mask includes all of these bits.
1380 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001381
Chris Lattnerbff91d92004-10-08 05:07:56 +00001382 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1383 // Okay, the xform is safe. Insert the new add pronto.
1384 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1385 LHS->getName()), I);
1386 return BinaryOperator::createAnd(NewAdd, C2);
1387 }
1388 }
1389 }
1390
Chris Lattnerd4252a72004-07-30 07:50:03 +00001391 // Try to fold constant add into select arguments.
1392 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001393 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001394 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001395 }
1396
Chris Lattner113f4f42002-06-25 16:13:24 +00001397 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001398}
1399
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001400// isSignBit - Return true if the value represented by the constant only has the
1401// highest order bit set.
1402static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001403 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001404 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001405}
1406
Chris Lattner022167f2004-03-13 00:11:49 +00001407/// RemoveNoopCast - Strip off nonconverting casts from the value.
1408///
1409static Value *RemoveNoopCast(Value *V) {
1410 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1411 const Type *CTy = CI->getType();
1412 const Type *OpTy = CI->getOperand(0)->getType();
1413 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001414 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001415 return RemoveNoopCast(CI->getOperand(0));
1416 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1417 return RemoveNoopCast(CI->getOperand(0));
1418 }
1419 return V;
1420}
1421
Chris Lattner113f4f42002-06-25 16:13:24 +00001422Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001423 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001424
Chris Lattnere6794492002-08-12 21:17:25 +00001425 if (Op0 == Op1) // sub X, X -> 0
1426 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001427
Chris Lattnere6794492002-08-12 21:17:25 +00001428 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001429 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001430 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001431
Chris Lattner81a7a232004-10-16 18:11:37 +00001432 if (isa<UndefValue>(Op0))
1433 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1434 if (isa<UndefValue>(Op1))
1435 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1436
Chris Lattner8f2f5982003-11-05 01:06:05 +00001437 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1438 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001439 if (C->isAllOnesValue())
1440 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001441
Chris Lattner8f2f5982003-11-05 01:06:05 +00001442 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001443 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001444 if (match(Op1, m_Not(m_Value(X))))
1445 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001446 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001447 // -((uint)X >> 31) -> ((int)X >> 31)
1448 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001449 if (C->isNullValue()) {
1450 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1451 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001452 if (SI->getOpcode() == Instruction::Shr)
1453 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1454 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001455 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001456 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001457 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001458 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001459 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001460 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001461 // Ok, the transformation is safe. Insert a cast of the incoming
1462 // value, then the new shift, then the new cast.
1463 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1464 SI->getOperand(0)->getName());
1465 Value *InV = InsertNewInstBefore(FirstCast, I);
1466 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1467 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001468 if (NewShift->getType() == I.getType())
1469 return NewShift;
1470 else {
1471 InV = InsertNewInstBefore(NewShift, I);
1472 return new CastInst(NewShift, I.getType());
1473 }
Chris Lattner92295c52004-03-12 23:53:13 +00001474 }
1475 }
Chris Lattner022167f2004-03-13 00:11:49 +00001476 }
Chris Lattner183b3362004-04-09 19:05:30 +00001477
1478 // Try to fold constant sub into select arguments.
1479 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001480 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001481 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001482
1483 if (isa<PHINode>(Op0))
1484 if (Instruction *NV = FoldOpIntoPhi(I))
1485 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001486 }
1487
Chris Lattnera9be4492005-04-07 16:15:25 +00001488 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1489 if (Op1I->getOpcode() == Instruction::Add &&
1490 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001491 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001492 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001493 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001494 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001495 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1496 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1497 // C1-(X+C2) --> (C1-C2)-X
1498 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1499 Op1I->getOperand(0));
1500 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001501 }
1502
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001503 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001504 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1505 // is not used by anyone else...
1506 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001507 if (Op1I->getOpcode() == Instruction::Sub &&
1508 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001509 // Swap the two operands of the subexpr...
1510 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1511 Op1I->setOperand(0, IIOp1);
1512 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001513
Chris Lattner3082c5a2003-02-18 19:28:33 +00001514 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001515 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001516 }
1517
1518 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1519 //
1520 if (Op1I->getOpcode() == Instruction::And &&
1521 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1522 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1523
Chris Lattner396dbfe2004-06-09 05:08:07 +00001524 Value *NewNot =
1525 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001526 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001527 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001528
Chris Lattner0aee4b72004-10-06 15:08:25 +00001529 // -(X sdiv C) -> (X sdiv -C)
1530 if (Op1I->getOpcode() == Instruction::Div)
1531 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001532 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001533 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001534 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001535 ConstantExpr::getNeg(DivRHS));
1536
Chris Lattner57c8d992003-02-18 19:57:07 +00001537 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001538 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001539 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001540 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001541 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001542 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001543 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001544 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001545 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001546
Chris Lattner47060462005-04-07 17:14:51 +00001547 if (!Op0->getType()->isFloatingPoint())
1548 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1549 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001550 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1551 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1552 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1553 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001554 } else if (Op0I->getOpcode() == Instruction::Sub) {
1555 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1556 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001557 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001558
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001559 ConstantInt *C1;
1560 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1561 if (X == Op1) { // X*C - X --> X * (C-1)
1562 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1563 return BinaryOperator::createMul(Op1, CP1);
1564 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001565
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001566 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1567 if (X == dyn_castFoldableMul(Op1, C2))
1568 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1569 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001570 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001571}
1572
Chris Lattnere79e8542004-02-23 06:38:22 +00001573/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1574/// really just returns true if the most significant (sign) bit is set.
1575static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1576 if (RHS->getType()->isSigned()) {
1577 // True if source is LHS < 0 or LHS <= -1
1578 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1579 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1580 } else {
1581 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1582 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1583 // the size of the integer type.
1584 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001585 return RHSC->getValue() ==
1586 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001587 if (Opcode == Instruction::SetGT)
1588 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001589 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001590 }
1591 return false;
1592}
1593
Chris Lattner113f4f42002-06-25 16:13:24 +00001594Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001595 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001596 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001597
Chris Lattner81a7a232004-10-16 18:11:37 +00001598 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1599 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1600
Chris Lattnere6794492002-08-12 21:17:25 +00001601 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001602 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1603 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001604
1605 // ((X << C1)*C2) == (X * (C2 << C1))
1606 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1607 if (SI->getOpcode() == Instruction::Shl)
1608 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001609 return BinaryOperator::createMul(SI->getOperand(0),
1610 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001611
Chris Lattnercce81be2003-09-11 22:24:54 +00001612 if (CI->isNullValue())
1613 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1614 if (CI->equalsInt(1)) // X * 1 == X
1615 return ReplaceInstUsesWith(I, Op0);
1616 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001617 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001618
Chris Lattnercce81be2003-09-11 22:24:54 +00001619 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001620 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1621 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001622 return new ShiftInst(Instruction::Shl, Op0,
1623 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001624 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001625 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001626 if (Op1F->isNullValue())
1627 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001628
Chris Lattner3082c5a2003-02-18 19:28:33 +00001629 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1630 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1631 if (Op1F->getValue() == 1.0)
1632 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1633 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001634
1635 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1636 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1637 isa<ConstantInt>(Op0I->getOperand(1))) {
1638 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1639 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1640 Op1, "tmp");
1641 InsertNewInstBefore(Add, I);
1642 Value *C1C2 = ConstantExpr::getMul(Op1,
1643 cast<Constant>(Op0I->getOperand(1)));
1644 return BinaryOperator::createAdd(Add, C1C2);
1645
1646 }
Chris Lattner183b3362004-04-09 19:05:30 +00001647
1648 // Try to fold constant mul into select arguments.
1649 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001650 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001651 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001652
1653 if (isa<PHINode>(Op0))
1654 if (Instruction *NV = FoldOpIntoPhi(I))
1655 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001656 }
1657
Chris Lattner934a64cf2003-03-10 23:23:04 +00001658 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1659 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001660 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001661
Chris Lattner2635b522004-02-23 05:39:21 +00001662 // If one of the operands of the multiply is a cast from a boolean value, then
1663 // we know the bool is either zero or one, so this is a 'masking' multiply.
1664 // See if we can simplify things based on how the boolean was originally
1665 // formed.
1666 CastInst *BoolCast = 0;
1667 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1668 if (CI->getOperand(0)->getType() == Type::BoolTy)
1669 BoolCast = CI;
1670 if (!BoolCast)
1671 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1672 if (CI->getOperand(0)->getType() == Type::BoolTy)
1673 BoolCast = CI;
1674 if (BoolCast) {
1675 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1676 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1677 const Type *SCOpTy = SCIOp0->getType();
1678
Chris Lattnere79e8542004-02-23 06:38:22 +00001679 // If the setcc is true iff the sign bit of X is set, then convert this
1680 // multiply into a shift/and combination.
1681 if (isa<ConstantInt>(SCIOp1) &&
1682 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001683 // Shift the X value right to turn it into "all signbits".
1684 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001685 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001686 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001687 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001688 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1689 SCIOp0->getName()), I);
1690 }
1691
1692 Value *V =
1693 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1694 BoolCast->getOperand(0)->getName()+
1695 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001696
1697 // If the multiply type is not the same as the source type, sign extend
1698 // or truncate to the multiply type.
1699 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001700 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001701
Chris Lattner2635b522004-02-23 05:39:21 +00001702 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001703 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001704 }
1705 }
1706 }
1707
Chris Lattner113f4f42002-06-25 16:13:24 +00001708 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001709}
1710
Chris Lattner113f4f42002-06-25 16:13:24 +00001711Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001712 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001713
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001714 if (isa<UndefValue>(Op0)) // undef / X -> 0
1715 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1716 if (isa<UndefValue>(Op1))
1717 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1718
1719 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001720 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001721 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001722 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001723
Chris Lattnere20c3342004-04-26 14:01:59 +00001724 // div X, -1 == -X
1725 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001726 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001727
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001728 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001729 if (LHS->getOpcode() == Instruction::Div)
1730 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001731 // (X / C1) / C2 -> X / (C1*C2)
1732 return BinaryOperator::createDiv(LHS->getOperand(0),
1733 ConstantExpr::getMul(RHS, LHSRHS));
1734 }
1735
Chris Lattner3082c5a2003-02-18 19:28:33 +00001736 // Check to see if this is an unsigned division with an exact power of 2,
1737 // if so, convert to a right shift.
1738 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1739 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001740 if (isPowerOf2_64(Val)) {
1741 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001742 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001743 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001744 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001745
Chris Lattner4ad08352004-10-09 02:50:40 +00001746 // -X/C -> X/-C
1747 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001748 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001749 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1750
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001751 if (!RHS->isNullValue()) {
1752 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001753 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001754 return R;
1755 if (isa<PHINode>(Op0))
1756 if (Instruction *NV = FoldOpIntoPhi(I))
1757 return NV;
1758 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001759 }
1760
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001761 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1762 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1763 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1764 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1765 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1766 if (STO->getValue() == 0) { // Couldn't be this argument.
1767 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001768 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001769 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001770 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001771 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001772 }
1773
Chris Lattner42362612005-04-08 04:03:26 +00001774 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001775 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1776 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001777 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1778 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1779 TC, SI->getName()+".t");
1780 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001781
Chris Lattner42362612005-04-08 04:03:26 +00001782 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1783 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1784 FC, SI->getName()+".f");
1785 FSI = InsertNewInstBefore(FSI, I);
1786 return new SelectInst(SI->getOperand(0), TSI, FSI);
1787 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001788 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001789
Chris Lattner3082c5a2003-02-18 19:28:33 +00001790 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001791 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001792 if (LHS->equalsInt(0))
1793 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1794
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001795 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001796 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001797 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001798 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1799 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001800 const Type *NTy = Op0->getType()->getUnsignedVersion();
1801 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1802 InsertNewInstBefore(LHS, I);
1803 Value *RHS;
1804 if (Constant *R = dyn_cast<Constant>(Op1))
1805 RHS = ConstantExpr::getCast(R, NTy);
1806 else
1807 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1808 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1809 InsertNewInstBefore(Div, I);
1810 return new CastInst(Div, I.getType());
1811 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001812 } else {
1813 // Known to be an unsigned division.
1814 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1815 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1816 if (RHSI->getOpcode() == Instruction::Shl &&
1817 isa<ConstantUInt>(RHSI->getOperand(0))) {
1818 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1819 if (isPowerOf2_64(C1)) {
1820 unsigned C2 = Log2_64(C1);
1821 Value *Add = RHSI->getOperand(1);
1822 if (C2) {
1823 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1824 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1825 "tmp"), I);
1826 }
1827 return new ShiftInst(Instruction::Shr, Op0, Add);
1828 }
1829 }
1830 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001831 }
1832
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001833 return 0;
1834}
1835
1836
Chris Lattner85dda9a2006-03-02 06:50:58 +00001837/// GetFactor - If we can prove that the specified value is at least a multiple
1838/// of some factor, return that factor.
1839static Constant *GetFactor(Value *V) {
1840 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1841 return CI;
1842
1843 // Unless we can be tricky, we know this is a multiple of 1.
1844 Constant *Result = ConstantInt::get(V->getType(), 1);
1845
1846 Instruction *I = dyn_cast<Instruction>(V);
1847 if (!I) return Result;
1848
1849 if (I->getOpcode() == Instruction::Mul) {
1850 // Handle multiplies by a constant, etc.
1851 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1852 GetFactor(I->getOperand(1)));
1853 } else if (I->getOpcode() == Instruction::Shl) {
1854 // (X<<C) -> X * (1 << C)
1855 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1856 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1857 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1858 }
1859 } else if (I->getOpcode() == Instruction::And) {
1860 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1861 // X & 0xFFF0 is known to be a multiple of 16.
1862 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1863 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1864 return ConstantExpr::getShl(Result,
1865 ConstantUInt::get(Type::UByteTy, Zeros));
1866 }
1867 } else if (I->getOpcode() == Instruction::Cast) {
1868 Value *Op = I->getOperand(0);
1869 // Only handle int->int casts.
1870 if (!Op->getType()->isInteger()) return Result;
1871 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1872 }
1873 return Result;
1874}
1875
Chris Lattner113f4f42002-06-25 16:13:24 +00001876Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001878
1879 // 0 % X == 0, we don't need to preserve faults!
1880 if (Constant *LHS = dyn_cast<Constant>(Op0))
1881 if (LHS->isNullValue())
1882 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1883
1884 if (isa<UndefValue>(Op0)) // undef % X -> 0
1885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1886 if (isa<UndefValue>(Op1))
1887 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1888
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001889 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001890 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001891 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001892 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001893 // X % -Y -> X % Y
1894 AddUsesToWorkList(I);
1895 I.setOperand(1, RHSNeg);
1896 return &I;
1897 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001898
1899 // If the top bits of both operands are zero (i.e. we can prove they are
1900 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001901 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1902 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001903 const Type *NTy = Op0->getType()->getUnsignedVersion();
1904 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1905 InsertNewInstBefore(LHS, I);
1906 Value *RHS;
1907 if (Constant *R = dyn_cast<Constant>(Op1))
1908 RHS = ConstantExpr::getCast(R, NTy);
1909 else
1910 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1911 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1912 InsertNewInstBefore(Rem, I);
1913 return new CastInst(Rem, I.getType());
1914 }
1915 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001916
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001917 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001918 // X % 0 == undef, we don't need to preserve faults!
1919 if (RHS->equalsInt(0))
1920 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1921
Chris Lattner3082c5a2003-02-18 19:28:33 +00001922 if (RHS->equalsInt(1)) // X % 1 == 0
1923 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1924
1925 // Check to see if this is an unsigned remainder with an exact power of 2,
1926 // if so, convert to a bitwise and.
1927 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001928 if (isPowerOf2_64(C->getValue()))
1929 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001930
Chris Lattnerb70f1412006-02-28 05:49:21 +00001931 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1932 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1933 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1934 return R;
1935 } else if (isa<PHINode>(Op0I)) {
1936 if (Instruction *NV = FoldOpIntoPhi(I))
1937 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00001938 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00001939
1940 // X*C1%C2 --> 0 iff C1%C2 == 0
1941 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1942 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00001943 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001944 }
1945
Chris Lattner2e90b732006-02-05 07:54:04 +00001946 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1947 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1948 if (I.getType()->isUnsigned() &&
1949 RHSI->getOpcode() == Instruction::Shl &&
1950 isa<ConstantUInt>(RHSI->getOperand(0))) {
1951 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1952 if (isPowerOf2_64(C1)) {
1953 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1954 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1955 "tmp"), I);
1956 return BinaryOperator::createAnd(Op0, Add);
1957 }
1958 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001959
1960 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1961 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1962 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1963 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1964 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1965 if (STO->getValue() == 0) { // Couldn't be this argument.
1966 I.setOperand(1, SFO);
1967 return &I;
1968 } else if (SFO->getValue() == 0) {
1969 I.setOperand(1, STO);
1970 return &I;
1971 }
1972
1973 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1974 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1975 SubOne(STO), SI->getName()+".t"), I);
1976 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1977 SubOne(SFO), SI->getName()+".f"), I);
1978 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1979 }
1980 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001981 }
1982
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001983 return 0;
1984}
1985
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001986// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001987static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001988 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1989 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001990
1991 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001992
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001993 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001994 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001995 int64_t Val = INT64_MAX; // All ones
1996 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1997 return CS->getValue() == Val-1;
1998}
1999
2000// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002001static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002002 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2003 return CU->getValue() == 1;
2004
2005 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002006
2007 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002008 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002009 int64_t Val = -1; // All ones
2010 Val <<= TypeBits-1; // Shift over to the right spot
2011 return CS->getValue() == Val+1;
2012}
2013
Chris Lattner35167c32004-06-09 07:59:58 +00002014// isOneBitSet - Return true if there is exactly one bit set in the specified
2015// constant.
2016static bool isOneBitSet(const ConstantInt *CI) {
2017 uint64_t V = CI->getRawValue();
2018 return V && (V & (V-1)) == 0;
2019}
2020
Chris Lattner8fc5af42004-09-23 21:46:38 +00002021#if 0 // Currently unused
2022// isLowOnes - Return true if the constant is of the form 0+1+.
2023static bool isLowOnes(const ConstantInt *CI) {
2024 uint64_t V = CI->getRawValue();
2025
2026 // There won't be bits set in parts that the type doesn't contain.
2027 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2028
2029 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2030 return U && V && (U & V) == 0;
2031}
2032#endif
2033
2034// isHighOnes - Return true if the constant is of the form 1+0+.
2035// This is the same as lowones(~X).
2036static bool isHighOnes(const ConstantInt *CI) {
2037 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002038 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002039
2040 // There won't be bits set in parts that the type doesn't contain.
2041 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2042
2043 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2044 return U && V && (U & V) == 0;
2045}
2046
2047
Chris Lattner3ac7c262003-08-13 20:16:26 +00002048/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2049/// are carefully arranged to allow folding of expressions such as:
2050///
2051/// (A < B) | (A > B) --> (A != B)
2052///
2053/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2054/// represents that the comparison is true if A == B, and bit value '1' is true
2055/// if A < B.
2056///
2057static unsigned getSetCondCode(const SetCondInst *SCI) {
2058 switch (SCI->getOpcode()) {
2059 // False -> 0
2060 case Instruction::SetGT: return 1;
2061 case Instruction::SetEQ: return 2;
2062 case Instruction::SetGE: return 3;
2063 case Instruction::SetLT: return 4;
2064 case Instruction::SetNE: return 5;
2065 case Instruction::SetLE: return 6;
2066 // True -> 7
2067 default:
2068 assert(0 && "Invalid SetCC opcode!");
2069 return 0;
2070 }
2071}
2072
2073/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2074/// opcode and two operands into either a constant true or false, or a brand new
2075/// SetCC instruction.
2076static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2077 switch (Opcode) {
2078 case 0: return ConstantBool::False;
2079 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2080 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2081 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2082 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2083 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2084 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2085 case 7: return ConstantBool::True;
2086 default: assert(0 && "Illegal SetCCCode!"); return 0;
2087 }
2088}
2089
2090// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2091struct FoldSetCCLogical {
2092 InstCombiner &IC;
2093 Value *LHS, *RHS;
2094 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2095 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2096 bool shouldApply(Value *V) const {
2097 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2098 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2099 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2100 return false;
2101 }
2102 Instruction *apply(BinaryOperator &Log) const {
2103 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2104 if (SCI->getOperand(0) != LHS) {
2105 assert(SCI->getOperand(1) == LHS);
2106 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2107 }
2108
2109 unsigned LHSCode = getSetCondCode(SCI);
2110 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2111 unsigned Code;
2112 switch (Log.getOpcode()) {
2113 case Instruction::And: Code = LHSCode & RHSCode; break;
2114 case Instruction::Or: Code = LHSCode | RHSCode; break;
2115 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002116 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002117 }
2118
2119 Value *RV = getSetCCValue(Code, LHS, RHS);
2120 if (Instruction *I = dyn_cast<Instruction>(RV))
2121 return I;
2122 // Otherwise, it's a constant boolean value...
2123 return IC.ReplaceInstUsesWith(Log, RV);
2124 }
2125};
2126
Chris Lattnerba1cb382003-09-19 17:17:26 +00002127// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2128// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2129// guaranteed to be either a shift instruction or a binary operator.
2130Instruction *InstCombiner::OptAndOp(Instruction *Op,
2131 ConstantIntegral *OpRHS,
2132 ConstantIntegral *AndRHS,
2133 BinaryOperator &TheAnd) {
2134 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002135 Constant *Together = 0;
2136 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002137 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002138
Chris Lattnerba1cb382003-09-19 17:17:26 +00002139 switch (Op->getOpcode()) {
2140 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002141 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002142 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2143 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002144 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002145 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002146 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002147 }
2148 break;
2149 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002150 if (Together == AndRHS) // (X | C) & C --> C
2151 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002152
Chris Lattner86102b82005-01-01 16:22:27 +00002153 if (Op->hasOneUse() && Together != OpRHS) {
2154 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2155 std::string Op0Name = Op->getName(); Op->setName("");
2156 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2157 InsertNewInstBefore(Or, TheAnd);
2158 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002159 }
2160 break;
2161 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002162 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002163 // Adding a one to a single bit bit-field should be turned into an XOR
2164 // of the bit. First thing to check is to see if this AND is with a
2165 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002166 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002167
2168 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002169 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002170
2171 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002172 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002173 // Ok, at this point, we know that we are masking the result of the
2174 // ADD down to exactly one bit. If the constant we are adding has
2175 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002176 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002177
Chris Lattnerba1cb382003-09-19 17:17:26 +00002178 // Check to see if any bits below the one bit set in AndRHSV are set.
2179 if ((AddRHS & (AndRHSV-1)) == 0) {
2180 // If not, the only thing that can effect the output of the AND is
2181 // the bit specified by AndRHSV. If that bit is set, the effect of
2182 // the XOR is to toggle the bit. If it is clear, then the ADD has
2183 // no effect.
2184 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2185 TheAnd.setOperand(0, X);
2186 return &TheAnd;
2187 } else {
2188 std::string Name = Op->getName(); Op->setName("");
2189 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002190 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002191 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002192 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002193 }
2194 }
2195 }
2196 }
2197 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002198
2199 case Instruction::Shl: {
2200 // We know that the AND will not produce any of the bits shifted in, so if
2201 // the anded constant includes them, clear them now!
2202 //
2203 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002204 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2205 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002206
Chris Lattner7e794272004-09-24 15:21:34 +00002207 if (CI == ShlMask) { // Masking out bits that the shift already masks
2208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2209 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002210 TheAnd.setOperand(1, CI);
2211 return &TheAnd;
2212 }
2213 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002214 }
Chris Lattner2da29172003-09-19 19:05:02 +00002215 case Instruction::Shr:
2216 // We know that the AND will not produce any of the bits shifted in, so if
2217 // the anded constant includes them, clear them now! This only applies to
2218 // unsigned shifts, because a signed shr may bring in set bits!
2219 //
2220 if (AndRHS->getType()->isUnsigned()) {
2221 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002222 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2223 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2224
2225 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2226 return ReplaceInstUsesWith(TheAnd, Op);
2227 } else if (CI != AndRHS) {
2228 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002229 return &TheAnd;
2230 }
Chris Lattner7e794272004-09-24 15:21:34 +00002231 } else { // Signed shr.
2232 // See if this is shifting in some sign extension, then masking it out
2233 // with an and.
2234 if (Op->hasOneUse()) {
2235 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2236 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2237 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002238 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002239 // Make the argument unsigned.
2240 Value *ShVal = Op->getOperand(0);
2241 ShVal = InsertCastBefore(ShVal,
2242 ShVal->getType()->getUnsignedVersion(),
2243 TheAnd);
2244 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2245 OpRHS, Op->getName()),
2246 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002247 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2248 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2249 TheAnd.getName()),
2250 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002251 return new CastInst(ShVal, Op->getType());
2252 }
2253 }
Chris Lattner2da29172003-09-19 19:05:02 +00002254 }
2255 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002256 }
2257 return 0;
2258}
2259
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002260
Chris Lattner6862fbd2004-09-29 17:40:11 +00002261/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2262/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2263/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2264/// insert new instructions.
2265Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2266 bool Inside, Instruction &IB) {
2267 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2268 "Lo is not <= Hi in range emission code!");
2269 if (Inside) {
2270 if (Lo == Hi) // Trivially false.
2271 return new SetCondInst(Instruction::SetNE, V, V);
2272 if (cast<ConstantIntegral>(Lo)->isMinValue())
2273 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002274
Chris Lattner6862fbd2004-09-29 17:40:11 +00002275 Constant *AddCST = ConstantExpr::getNeg(Lo);
2276 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2277 InsertNewInstBefore(Add, IB);
2278 // Convert to unsigned for the comparison.
2279 const Type *UnsType = Add->getType()->getUnsignedVersion();
2280 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2281 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2282 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2283 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2284 }
2285
2286 if (Lo == Hi) // Trivially true.
2287 return new SetCondInst(Instruction::SetEQ, V, V);
2288
2289 Hi = SubOne(cast<ConstantInt>(Hi));
2290 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2291 return new SetCondInst(Instruction::SetGT, V, Hi);
2292
2293 // Emit X-Lo > Hi-Lo-1
2294 Constant *AddCST = ConstantExpr::getNeg(Lo);
2295 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2296 InsertNewInstBefore(Add, IB);
2297 // Convert to unsigned for the comparison.
2298 const Type *UnsType = Add->getType()->getUnsignedVersion();
2299 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2300 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2301 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2302 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2303}
2304
Chris Lattnerb4b25302005-09-18 07:22:02 +00002305// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2306// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2307// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2308// not, since all 1s are not contiguous.
2309static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2310 uint64_t V = Val->getRawValue();
2311 if (!isShiftedMask_64(V)) return false;
2312
2313 // look for the first zero bit after the run of ones
2314 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2315 // look for the first non-zero bit
2316 ME = 64-CountLeadingZeros_64(V);
2317 return true;
2318}
2319
2320
2321
2322/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2323/// where isSub determines whether the operator is a sub. If we can fold one of
2324/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002325///
2326/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2327/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2328/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2329///
2330/// return (A +/- B).
2331///
2332Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2333 ConstantIntegral *Mask, bool isSub,
2334 Instruction &I) {
2335 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2336 if (!LHSI || LHSI->getNumOperands() != 2 ||
2337 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2338
2339 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2340
2341 switch (LHSI->getOpcode()) {
2342 default: return 0;
2343 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002344 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2345 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2346 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2347 break;
2348
2349 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2350 // part, we don't need any explicit masks to take them out of A. If that
2351 // is all N is, ignore it.
2352 unsigned MB, ME;
2353 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002354 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2355 Mask >>= 64-MB+1;
2356 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002357 break;
2358 }
2359 }
Chris Lattneraf517572005-09-18 04:24:45 +00002360 return 0;
2361 case Instruction::Or:
2362 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002363 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2364 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2365 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002366 break;
2367 return 0;
2368 }
2369
2370 Instruction *New;
2371 if (isSub)
2372 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2373 else
2374 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2375 return InsertNewInstBefore(New, I);
2376}
2377
Chris Lattner113f4f42002-06-25 16:13:24 +00002378Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002379 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002380 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002381
Chris Lattner81a7a232004-10-16 18:11:37 +00002382 if (isa<UndefValue>(Op1)) // X & undef -> 0
2383 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2384
Chris Lattner86102b82005-01-01 16:22:27 +00002385 // and X, X = X
2386 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002387 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002388
Chris Lattner5b2edb12006-02-12 08:02:11 +00002389 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002390 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002391 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002392 if (!isa<PackedType>(I.getType()) &&
2393 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002394 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002395 return &I;
2396
Chris Lattner86102b82005-01-01 16:22:27 +00002397 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002398 uint64_t AndRHSMask = AndRHS->getZExtValue();
2399 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002400 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002401
Chris Lattnerba1cb382003-09-19 17:17:26 +00002402 // Optimize a variety of ((val OP C1) & C2) combinations...
2403 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2404 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002405 Value *Op0LHS = Op0I->getOperand(0);
2406 Value *Op0RHS = Op0I->getOperand(1);
2407 switch (Op0I->getOpcode()) {
2408 case Instruction::Xor:
2409 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002410 // If the mask is only needed on one incoming arm, push it up.
2411 if (Op0I->hasOneUse()) {
2412 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2413 // Not masking anything out for the LHS, move to RHS.
2414 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2415 Op0RHS->getName()+".masked");
2416 InsertNewInstBefore(NewRHS, I);
2417 return BinaryOperator::create(
2418 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002419 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002420 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002421 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2422 // Not masking anything out for the RHS, move to LHS.
2423 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2424 Op0LHS->getName()+".masked");
2425 InsertNewInstBefore(NewLHS, I);
2426 return BinaryOperator::create(
2427 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2428 }
2429 }
2430
Chris Lattner86102b82005-01-01 16:22:27 +00002431 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002432 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002433 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2434 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2435 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2436 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2437 return BinaryOperator::createAnd(V, AndRHS);
2438 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2439 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002440 break;
2441
2442 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002443 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2444 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2445 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2446 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2447 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002448 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002449 }
2450
Chris Lattner16464b32003-07-23 19:25:52 +00002451 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002452 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002453 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002454 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2455 const Type *SrcTy = CI->getOperand(0)->getType();
2456
Chris Lattner2c14cf72005-08-07 07:03:10 +00002457 // If this is an integer truncation or change from signed-to-unsigned, and
2458 // if the source is an and/or with immediate, transform it. This
2459 // frequently occurs for bitfield accesses.
2460 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2461 if (SrcTy->getPrimitiveSizeInBits() >=
2462 I.getType()->getPrimitiveSizeInBits() &&
2463 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002464 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002465 if (CastOp->getOpcode() == Instruction::And) {
2466 // Change: and (cast (and X, C1) to T), C2
2467 // into : and (cast X to T), trunc(C1)&C2
2468 // This will folds the two ands together, which may allow other
2469 // simplifications.
2470 Instruction *NewCast =
2471 new CastInst(CastOp->getOperand(0), I.getType(),
2472 CastOp->getName()+".shrunk");
2473 NewCast = InsertNewInstBefore(NewCast, I);
2474
2475 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2476 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2477 return BinaryOperator::createAnd(NewCast, C3);
2478 } else if (CastOp->getOpcode() == Instruction::Or) {
2479 // Change: and (cast (or X, C1) to T), C2
2480 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2481 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2482 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2483 return ReplaceInstUsesWith(I, AndRHS);
2484 }
2485 }
Chris Lattner33217db2003-07-23 19:36:21 +00002486 }
Chris Lattner183b3362004-04-09 19:05:30 +00002487
2488 // Try to fold constant and into select arguments.
2489 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002490 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002491 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002492 if (isa<PHINode>(Op0))
2493 if (Instruction *NV = FoldOpIntoPhi(I))
2494 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002495 }
2496
Chris Lattnerbb74e222003-03-10 23:06:50 +00002497 Value *Op0NotVal = dyn_castNotVal(Op0);
2498 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002499
Chris Lattner023a4832004-06-18 06:07:51 +00002500 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2502
Misha Brukman9c003d82004-07-30 12:50:08 +00002503 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002504 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002505 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2506 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002507 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002508 return BinaryOperator::createNot(Or);
2509 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002510
2511 {
2512 Value *A = 0, *B = 0;
2513 ConstantInt *C1 = 0, *C2 = 0;
2514 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2515 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2516 return ReplaceInstUsesWith(I, Op1);
2517 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2518 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2519 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002520
2521 if (Op0->hasOneUse() &&
2522 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2523 if (A == Op1) { // (A^B)&A -> A&(A^B)
2524 I.swapOperands(); // Simplify below
2525 std::swap(Op0, Op1);
2526 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2527 cast<BinaryOperator>(Op0)->swapOperands();
2528 I.swapOperands(); // Simplify below
2529 std::swap(Op0, Op1);
2530 }
2531 }
2532 if (Op1->hasOneUse() &&
2533 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2534 if (B == Op0) { // B&(A^B) -> B&(B^A)
2535 cast<BinaryOperator>(Op1)->swapOperands();
2536 std::swap(A, B);
2537 }
2538 if (A == Op0) { // A&(A^B) -> A & ~B
2539 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2540 InsertNewInstBefore(NotB, I);
2541 return BinaryOperator::createAnd(A, NotB);
2542 }
2543 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002544 }
2545
Chris Lattner3082c5a2003-02-18 19:28:33 +00002546
Chris Lattner623826c2004-09-28 21:48:02 +00002547 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2548 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002549 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2550 return R;
2551
Chris Lattner623826c2004-09-28 21:48:02 +00002552 Value *LHSVal, *RHSVal;
2553 ConstantInt *LHSCst, *RHSCst;
2554 Instruction::BinaryOps LHSCC, RHSCC;
2555 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2556 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2557 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2558 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002559 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002560 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2561 // Ensure that the larger constant is on the RHS.
2562 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2563 SetCondInst *LHS = cast<SetCondInst>(Op0);
2564 if (cast<ConstantBool>(Cmp)->getValue()) {
2565 std::swap(LHS, RHS);
2566 std::swap(LHSCst, RHSCst);
2567 std::swap(LHSCC, RHSCC);
2568 }
2569
2570 // At this point, we know we have have two setcc instructions
2571 // comparing a value against two constants and and'ing the result
2572 // together. Because of the above check, we know that we only have
2573 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2574 // FoldSetCCLogical check above), that the two constants are not
2575 // equal.
2576 assert(LHSCst != RHSCst && "Compares not folded above?");
2577
2578 switch (LHSCC) {
2579 default: assert(0 && "Unknown integer condition code!");
2580 case Instruction::SetEQ:
2581 switch (RHSCC) {
2582 default: assert(0 && "Unknown integer condition code!");
2583 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2584 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2585 return ReplaceInstUsesWith(I, ConstantBool::False);
2586 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2587 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2588 return ReplaceInstUsesWith(I, LHS);
2589 }
2590 case Instruction::SetNE:
2591 switch (RHSCC) {
2592 default: assert(0 && "Unknown integer condition code!");
2593 case Instruction::SetLT:
2594 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2595 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2596 break; // (X != 13 & X < 15) -> no change
2597 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2598 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2599 return ReplaceInstUsesWith(I, RHS);
2600 case Instruction::SetNE:
2601 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2602 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2603 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2604 LHSVal->getName()+".off");
2605 InsertNewInstBefore(Add, I);
2606 const Type *UnsType = Add->getType()->getUnsignedVersion();
2607 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2608 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2609 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2610 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2611 }
2612 break; // (X != 13 & X != 15) -> no change
2613 }
2614 break;
2615 case Instruction::SetLT:
2616 switch (RHSCC) {
2617 default: assert(0 && "Unknown integer condition code!");
2618 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2619 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2620 return ReplaceInstUsesWith(I, ConstantBool::False);
2621 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2622 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2623 return ReplaceInstUsesWith(I, LHS);
2624 }
2625 case Instruction::SetGT:
2626 switch (RHSCC) {
2627 default: assert(0 && "Unknown integer condition code!");
2628 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2629 return ReplaceInstUsesWith(I, LHS);
2630 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2631 return ReplaceInstUsesWith(I, RHS);
2632 case Instruction::SetNE:
2633 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2634 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2635 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002636 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2637 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002638 }
2639 }
2640 }
2641 }
2642
Chris Lattner3af10532006-05-05 06:39:07 +00002643 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2644 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002645 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002646 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002647 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
2648 !SrcTy->isLosslesslyConvertibleTo(Op0C->getType())) {
Chris Lattner3af10532006-05-05 06:39:07 +00002649 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2650 Op1C->getOperand(0),
2651 I.getName());
2652 InsertNewInstBefore(NewOp, I);
2653 return new CastInst(NewOp, I.getType());
2654 }
2655 }
2656
Chris Lattner113f4f42002-06-25 16:13:24 +00002657 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002658}
2659
Chris Lattner113f4f42002-06-25 16:13:24 +00002660Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002661 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002662 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002663
Chris Lattner81a7a232004-10-16 18:11:37 +00002664 if (isa<UndefValue>(Op1))
2665 return ReplaceInstUsesWith(I, // X | undef -> -1
2666 ConstantIntegral::getAllOnesValue(I.getType()));
2667
Chris Lattner5b2edb12006-02-12 08:02:11 +00002668 // or X, X = X
2669 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002670 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002671
Chris Lattner5b2edb12006-02-12 08:02:11 +00002672 // See if we can simplify any instructions used by the instruction whose sole
2673 // purpose is to compute bits we don't care about.
2674 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002675 if (!isa<PackedType>(I.getType()) &&
2676 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002677 KnownZero, KnownOne))
2678 return &I;
2679
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002680 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002681 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002682 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002683 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2684 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002685 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2686 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002687 InsertNewInstBefore(Or, I);
2688 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2689 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002690
Chris Lattnerd4252a72004-07-30 07:50:03 +00002691 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2692 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2693 std::string Op0Name = Op0->getName(); Op0->setName("");
2694 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2695 InsertNewInstBefore(Or, I);
2696 return BinaryOperator::createXor(Or,
2697 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002698 }
Chris Lattner183b3362004-04-09 19:05:30 +00002699
2700 // Try to fold constant and into select arguments.
2701 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002702 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002703 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002704 if (isa<PHINode>(Op0))
2705 if (Instruction *NV = FoldOpIntoPhi(I))
2706 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002707 }
2708
Chris Lattner330628a2006-01-06 17:59:59 +00002709 Value *A = 0, *B = 0;
2710 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002711
2712 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2713 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2714 return ReplaceInstUsesWith(I, Op1);
2715 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2716 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2717 return ReplaceInstUsesWith(I, Op0);
2718
Chris Lattnerb62f5082005-05-09 04:58:36 +00002719 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2720 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002721 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002722 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2723 Op0->setName("");
2724 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2725 }
2726
2727 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2728 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002729 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002730 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2731 Op0->setName("");
2732 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2733 }
2734
Chris Lattner15212982005-09-18 03:42:07 +00002735 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002736 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002737 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2738
2739 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2740 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2741
2742
Chris Lattner01f56c62005-09-18 06:02:59 +00002743 // If we have: ((V + N) & C1) | (V & C2)
2744 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2745 // replace with V+N.
2746 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002747 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002748 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2749 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2750 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002751 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002752 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002753 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002754 return ReplaceInstUsesWith(I, A);
2755 }
2756 // Or commutes, try both ways.
2757 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2758 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2759 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002760 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002761 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002762 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002763 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002764 }
2765 }
2766 }
Chris Lattner812aab72003-08-12 19:11:07 +00002767
Chris Lattnerd4252a72004-07-30 07:50:03 +00002768 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2769 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002770 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002771 ConstantIntegral::getAllOnesValue(I.getType()));
2772 } else {
2773 A = 0;
2774 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002775 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002776 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2777 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002778 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002779 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002780
Misha Brukman9c003d82004-07-30 12:50:08 +00002781 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002782 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2783 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2784 I.getName()+".demorgan"), I);
2785 return BinaryOperator::createNot(And);
2786 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002787 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002788
Chris Lattner3ac7c262003-08-13 20:16:26 +00002789 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002790 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002791 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2792 return R;
2793
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002794 Value *LHSVal, *RHSVal;
2795 ConstantInt *LHSCst, *RHSCst;
2796 Instruction::BinaryOps LHSCC, RHSCC;
2797 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2798 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2799 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2800 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002801 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002802 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2803 // Ensure that the larger constant is on the RHS.
2804 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2805 SetCondInst *LHS = cast<SetCondInst>(Op0);
2806 if (cast<ConstantBool>(Cmp)->getValue()) {
2807 std::swap(LHS, RHS);
2808 std::swap(LHSCst, RHSCst);
2809 std::swap(LHSCC, RHSCC);
2810 }
2811
2812 // At this point, we know we have have two setcc instructions
2813 // comparing a value against two constants and or'ing the result
2814 // together. Because of the above check, we know that we only have
2815 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2816 // FoldSetCCLogical check above), that the two constants are not
2817 // equal.
2818 assert(LHSCst != RHSCst && "Compares not folded above?");
2819
2820 switch (LHSCC) {
2821 default: assert(0 && "Unknown integer condition code!");
2822 case Instruction::SetEQ:
2823 switch (RHSCC) {
2824 default: assert(0 && "Unknown integer condition code!");
2825 case Instruction::SetEQ:
2826 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2827 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2828 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2829 LHSVal->getName()+".off");
2830 InsertNewInstBefore(Add, I);
2831 const Type *UnsType = Add->getType()->getUnsignedVersion();
2832 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2833 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2834 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2835 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2836 }
2837 break; // (X == 13 | X == 15) -> no change
2838
Chris Lattner5c219462005-04-19 06:04:18 +00002839 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2840 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002841 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2842 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2843 return ReplaceInstUsesWith(I, RHS);
2844 }
2845 break;
2846 case Instruction::SetNE:
2847 switch (RHSCC) {
2848 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002849 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2850 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2851 return ReplaceInstUsesWith(I, LHS);
2852 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002853 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002854 return ReplaceInstUsesWith(I, ConstantBool::True);
2855 }
2856 break;
2857 case Instruction::SetLT:
2858 switch (RHSCC) {
2859 default: assert(0 && "Unknown integer condition code!");
2860 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2861 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002862 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2863 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002864 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2865 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2866 return ReplaceInstUsesWith(I, RHS);
2867 }
2868 break;
2869 case Instruction::SetGT:
2870 switch (RHSCC) {
2871 default: assert(0 && "Unknown integer condition code!");
2872 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2873 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2874 return ReplaceInstUsesWith(I, LHS);
2875 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2876 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2877 return ReplaceInstUsesWith(I, ConstantBool::True);
2878 }
2879 }
2880 }
2881 }
Chris Lattner3af10532006-05-05 06:39:07 +00002882
2883 // fold (or (cast A), (cast B)) -> (cast (or A, B))
2884 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002885 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002886 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002887 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
2888 !SrcTy->isLosslesslyConvertibleTo(Op0C->getType())) {
Chris Lattner3af10532006-05-05 06:39:07 +00002889 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
2890 Op1C->getOperand(0),
2891 I.getName());
2892 InsertNewInstBefore(NewOp, I);
2893 return new CastInst(NewOp, I.getType());
2894 }
2895 }
2896
Chris Lattner15212982005-09-18 03:42:07 +00002897
Chris Lattner113f4f42002-06-25 16:13:24 +00002898 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002899}
2900
Chris Lattnerc2076352004-02-16 01:20:27 +00002901// XorSelf - Implements: X ^ X --> 0
2902struct XorSelf {
2903 Value *RHS;
2904 XorSelf(Value *rhs) : RHS(rhs) {}
2905 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2906 Instruction *apply(BinaryOperator &Xor) const {
2907 return &Xor;
2908 }
2909};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002910
2911
Chris Lattner113f4f42002-06-25 16:13:24 +00002912Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002913 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002915
Chris Lattner81a7a232004-10-16 18:11:37 +00002916 if (isa<UndefValue>(Op1))
2917 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2918
Chris Lattnerc2076352004-02-16 01:20:27 +00002919 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2920 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2921 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002922 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002923 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00002924
2925 // See if we can simplify any instructions used by the instruction whose sole
2926 // purpose is to compute bits we don't care about.
2927 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002928 if (!isa<PackedType>(I.getType()) &&
2929 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002930 KnownZero, KnownOne))
2931 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002932
Chris Lattner97638592003-07-23 21:37:07 +00002933 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00002934 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002935 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002936 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002937 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002938 return new SetCondInst(SCI->getInverseCondition(),
2939 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002940
Chris Lattner8f2f5982003-11-05 01:06:05 +00002941 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002942 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2943 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002944 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2945 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002946 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002947 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002948 }
Chris Lattner023a4832004-06-18 06:07:51 +00002949
2950 // ~(~X & Y) --> (X | ~Y)
2951 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2952 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2953 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2954 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002955 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002956 Op0I->getOperand(1)->getName()+".not");
2957 InsertNewInstBefore(NotY, I);
2958 return BinaryOperator::createOr(Op0NotVal, NotY);
2959 }
2960 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002961
Chris Lattner97638592003-07-23 21:37:07 +00002962 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00002963 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00002964 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002965 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002966 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2967 return BinaryOperator::createSub(
2968 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002969 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002970 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002971 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00002972 } else if (Op0I->getOpcode() == Instruction::Or) {
2973 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2974 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2975 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2976 // Anything in both C1 and C2 is known to be zero, remove it from
2977 // NewRHS.
2978 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2979 NewRHS = ConstantExpr::getAnd(NewRHS,
2980 ConstantExpr::getNot(CommonBits));
2981 WorkList.push_back(Op0I);
2982 I.setOperand(0, Op0I->getOperand(0));
2983 I.setOperand(1, NewRHS);
2984 return &I;
2985 }
Chris Lattner97638592003-07-23 21:37:07 +00002986 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002987 }
Chris Lattner183b3362004-04-09 19:05:30 +00002988
2989 // Try to fold constant and into select arguments.
2990 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002991 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002992 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002993 if (isa<PHINode>(Op0))
2994 if (Instruction *NV = FoldOpIntoPhi(I))
2995 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002996 }
2997
Chris Lattnerbb74e222003-03-10 23:06:50 +00002998 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002999 if (X == Op1)
3000 return ReplaceInstUsesWith(I,
3001 ConstantIntegral::getAllOnesValue(I.getType()));
3002
Chris Lattnerbb74e222003-03-10 23:06:50 +00003003 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003004 if (X == Op0)
3005 return ReplaceInstUsesWith(I,
3006 ConstantIntegral::getAllOnesValue(I.getType()));
3007
Chris Lattnerdcd07922006-04-01 08:03:55 +00003008 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003009 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003010 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003011 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003012 I.swapOperands();
3013 std::swap(Op0, Op1);
3014 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003015 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003016 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003017 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003018 } else if (Op1I->getOpcode() == Instruction::Xor) {
3019 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3020 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3021 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3022 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003023 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3024 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3025 Op1I->swapOperands();
3026 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3027 I.swapOperands(); // Simplified below.
3028 std::swap(Op0, Op1);
3029 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003030 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003031
Chris Lattnerdcd07922006-04-01 08:03:55 +00003032 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003033 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003034 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003035 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003036 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003037 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3038 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003039 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003040 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003041 } else if (Op0I->getOpcode() == Instruction::Xor) {
3042 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3043 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3044 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3045 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003046 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3047 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3048 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003049 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3050 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003051 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3052 InsertNewInstBefore(N, I);
3053 return BinaryOperator::createAnd(N, Op1);
3054 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003055 }
3056
Chris Lattner3ac7c262003-08-13 20:16:26 +00003057 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3058 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3059 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3060 return R;
3061
Chris Lattner3af10532006-05-05 06:39:07 +00003062 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3063 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003064 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003065 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003066 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3067 !SrcTy->isLosslesslyConvertibleTo(Op0C->getType())) {
Chris Lattner3af10532006-05-05 06:39:07 +00003068 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3069 Op1C->getOperand(0),
3070 I.getName());
3071 InsertNewInstBefore(NewOp, I);
3072 return new CastInst(NewOp, I.getType());
3073 }
3074 }
3075
Chris Lattner113f4f42002-06-25 16:13:24 +00003076 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003077}
3078
Chris Lattner6862fbd2004-09-29 17:40:11 +00003079/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3080/// overflowed for this type.
3081static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3082 ConstantInt *In2) {
3083 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3084 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3085}
3086
3087static bool isPositive(ConstantInt *C) {
3088 return cast<ConstantSInt>(C)->getValue() >= 0;
3089}
3090
3091/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3092/// overflowed for this type.
3093static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3094 ConstantInt *In2) {
3095 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3096
3097 if (In1->getType()->isUnsigned())
3098 return cast<ConstantUInt>(Result)->getValue() <
3099 cast<ConstantUInt>(In1)->getValue();
3100 if (isPositive(In1) != isPositive(In2))
3101 return false;
3102 if (isPositive(In1))
3103 return cast<ConstantSInt>(Result)->getValue() <
3104 cast<ConstantSInt>(In1)->getValue();
3105 return cast<ConstantSInt>(Result)->getValue() >
3106 cast<ConstantSInt>(In1)->getValue();
3107}
3108
Chris Lattner0798af32005-01-13 20:14:25 +00003109/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3110/// code necessary to compute the offset from the base pointer (without adding
3111/// in the base pointer). Return the result as a signed integer of intptr size.
3112static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3113 TargetData &TD = IC.getTargetData();
3114 gep_type_iterator GTI = gep_type_begin(GEP);
3115 const Type *UIntPtrTy = TD.getIntPtrType();
3116 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3117 Value *Result = Constant::getNullValue(SIntPtrTy);
3118
3119 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003120 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003121
Chris Lattner0798af32005-01-13 20:14:25 +00003122 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3123 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003124 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003125 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3126 SIntPtrTy);
3127 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3128 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003129 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003130 Scale = ConstantExpr::getMul(OpC, Scale);
3131 if (Constant *RC = dyn_cast<Constant>(Result))
3132 Result = ConstantExpr::getAdd(RC, Scale);
3133 else {
3134 // Emit an add instruction.
3135 Result = IC.InsertNewInstBefore(
3136 BinaryOperator::createAdd(Result, Scale,
3137 GEP->getName()+".offs"), I);
3138 }
3139 }
3140 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003141 // Convert to correct type.
3142 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3143 Op->getName()+".c"), I);
3144 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003145 // We'll let instcombine(mul) convert this to a shl if possible.
3146 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3147 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003148
3149 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003150 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003151 GEP->getName()+".offs"), I);
3152 }
3153 }
3154 return Result;
3155}
3156
3157/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3158/// else. At this point we know that the GEP is on the LHS of the comparison.
3159Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3160 Instruction::BinaryOps Cond,
3161 Instruction &I) {
3162 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003163
3164 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3165 if (isa<PointerType>(CI->getOperand(0)->getType()))
3166 RHS = CI->getOperand(0);
3167
Chris Lattner0798af32005-01-13 20:14:25 +00003168 Value *PtrBase = GEPLHS->getOperand(0);
3169 if (PtrBase == RHS) {
3170 // As an optimization, we don't actually have to compute the actual value of
3171 // OFFSET if this is a seteq or setne comparison, just return whether each
3172 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003173 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3174 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003175 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3176 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003177 bool EmitIt = true;
3178 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3179 if (isa<UndefValue>(C)) // undef index -> undef.
3180 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3181 if (C->isNullValue())
3182 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003183 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3184 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003185 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003186 return ReplaceInstUsesWith(I, // No comparison is needed here.
3187 ConstantBool::get(Cond == Instruction::SetNE));
3188 }
3189
3190 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003191 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003192 new SetCondInst(Cond, GEPLHS->getOperand(i),
3193 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3194 if (InVal == 0)
3195 InVal = Comp;
3196 else {
3197 InVal = InsertNewInstBefore(InVal, I);
3198 InsertNewInstBefore(Comp, I);
3199 if (Cond == Instruction::SetNE) // True if any are unequal
3200 InVal = BinaryOperator::createOr(InVal, Comp);
3201 else // True if all are equal
3202 InVal = BinaryOperator::createAnd(InVal, Comp);
3203 }
3204 }
3205 }
3206
3207 if (InVal)
3208 return InVal;
3209 else
3210 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3211 ConstantBool::get(Cond == Instruction::SetEQ));
3212 }
Chris Lattner0798af32005-01-13 20:14:25 +00003213
3214 // Only lower this if the setcc is the only user of the GEP or if we expect
3215 // the result to fold to a constant!
3216 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3217 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3218 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3219 return new SetCondInst(Cond, Offset,
3220 Constant::getNullValue(Offset->getType()));
3221 }
3222 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003223 // If the base pointers are different, but the indices are the same, just
3224 // compare the base pointer.
3225 if (PtrBase != GEPRHS->getOperand(0)) {
3226 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003227 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003228 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003229 if (IndicesTheSame)
3230 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3231 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3232 IndicesTheSame = false;
3233 break;
3234 }
3235
3236 // If all indices are the same, just compare the base pointers.
3237 if (IndicesTheSame)
3238 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3239 GEPRHS->getOperand(0));
3240
3241 // Otherwise, the base pointers are different and the indices are
3242 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003243 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003244 }
Chris Lattner0798af32005-01-13 20:14:25 +00003245
Chris Lattner81e84172005-01-13 22:25:21 +00003246 // If one of the GEPs has all zero indices, recurse.
3247 bool AllZeros = true;
3248 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3249 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3250 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3251 AllZeros = false;
3252 break;
3253 }
3254 if (AllZeros)
3255 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3256 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003257
3258 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003259 AllZeros = true;
3260 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3261 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3262 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3263 AllZeros = false;
3264 break;
3265 }
3266 if (AllZeros)
3267 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3268
Chris Lattner4fa89822005-01-14 00:20:05 +00003269 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3270 // If the GEPs only differ by one index, compare it.
3271 unsigned NumDifferences = 0; // Keep track of # differences.
3272 unsigned DiffOperand = 0; // The operand that differs.
3273 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3274 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003275 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3276 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003277 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003278 NumDifferences = 2;
3279 break;
3280 } else {
3281 if (NumDifferences++) break;
3282 DiffOperand = i;
3283 }
3284 }
3285
3286 if (NumDifferences == 0) // SAME GEP?
3287 return ReplaceInstUsesWith(I, // No comparison is needed here.
3288 ConstantBool::get(Cond == Instruction::SetEQ));
3289 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003290 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3291 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003292
3293 // Convert the operands to signed values to make sure to perform a
3294 // signed comparison.
3295 const Type *NewTy = LHSV->getType()->getSignedVersion();
3296 if (LHSV->getType() != NewTy)
3297 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3298 LHSV->getName()), I);
3299 if (RHSV->getType() != NewTy)
3300 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3301 RHSV->getName()), I);
3302 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003303 }
3304 }
3305
Chris Lattner0798af32005-01-13 20:14:25 +00003306 // Only lower this if the setcc is the only user of the GEP or if we expect
3307 // the result to fold to a constant!
3308 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3309 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3310 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3311 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3312 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3313 return new SetCondInst(Cond, L, R);
3314 }
3315 }
3316 return 0;
3317}
3318
3319
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003320Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003321 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003322 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3323 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003324
3325 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003326 if (Op0 == Op1)
3327 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003328
Chris Lattner81a7a232004-10-16 18:11:37 +00003329 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3330 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3331
Chris Lattner15ff1e12004-11-14 07:33:16 +00003332 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3333 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003334 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3335 isa<ConstantPointerNull>(Op0)) &&
3336 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003337 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003338 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3339
3340 // setcc's with boolean values can always be turned into bitwise operations
3341 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003342 switch (I.getOpcode()) {
3343 default: assert(0 && "Invalid setcc instruction!");
3344 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003345 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003346 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003347 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003348 }
Chris Lattner4456da62004-08-11 00:50:51 +00003349 case Instruction::SetNE:
3350 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003351
Chris Lattner4456da62004-08-11 00:50:51 +00003352 case Instruction::SetGT:
3353 std::swap(Op0, Op1); // Change setgt -> setlt
3354 // FALL THROUGH
3355 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3356 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3357 InsertNewInstBefore(Not, I);
3358 return BinaryOperator::createAnd(Not, Op1);
3359 }
3360 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003361 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003362 // FALL THROUGH
3363 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3364 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3365 InsertNewInstBefore(Not, I);
3366 return BinaryOperator::createOr(Not, Op1);
3367 }
3368 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003369 }
3370
Chris Lattner2dd01742004-06-09 04:24:29 +00003371 // See if we are doing a comparison between a constant and an instruction that
3372 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003373 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003374 // Check to see if we are comparing against the minimum or maximum value...
3375 if (CI->isMinValue()) {
3376 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3377 return ReplaceInstUsesWith(I, ConstantBool::False);
3378 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3379 return ReplaceInstUsesWith(I, ConstantBool::True);
3380 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3381 return BinaryOperator::createSetEQ(Op0, Op1);
3382 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3383 return BinaryOperator::createSetNE(Op0, Op1);
3384
3385 } else if (CI->isMaxValue()) {
3386 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3387 return ReplaceInstUsesWith(I, ConstantBool::False);
3388 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3389 return ReplaceInstUsesWith(I, ConstantBool::True);
3390 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3391 return BinaryOperator::createSetEQ(Op0, Op1);
3392 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3393 return BinaryOperator::createSetNE(Op0, Op1);
3394
3395 // Comparing against a value really close to min or max?
3396 } else if (isMinValuePlusOne(CI)) {
3397 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3398 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3399 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3400 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3401
3402 } else if (isMaxValueMinusOne(CI)) {
3403 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3404 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3405 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3406 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3407 }
3408
3409 // If we still have a setle or setge instruction, turn it into the
3410 // appropriate setlt or setgt instruction. Since the border cases have
3411 // already been handled above, this requires little checking.
3412 //
3413 if (I.getOpcode() == Instruction::SetLE)
3414 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3415 if (I.getOpcode() == Instruction::SetGE)
3416 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3417
Chris Lattneree0f2802006-02-12 02:07:56 +00003418
3419 // See if we can fold the comparison based on bits known to be zero or one
3420 // in the input.
3421 uint64_t KnownZero, KnownOne;
3422 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3423 KnownZero, KnownOne, 0))
3424 return &I;
3425
3426 // Given the known and unknown bits, compute a range that the LHS could be
3427 // in.
3428 if (KnownOne | KnownZero) {
3429 if (Ty->isUnsigned()) { // Unsigned comparison.
3430 uint64_t Min, Max;
3431 uint64_t RHSVal = CI->getZExtValue();
3432 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3433 Min, Max);
3434 switch (I.getOpcode()) { // LE/GE have been folded already.
3435 default: assert(0 && "Unknown setcc opcode!");
3436 case Instruction::SetEQ:
3437 if (Max < RHSVal || Min > RHSVal)
3438 return ReplaceInstUsesWith(I, ConstantBool::False);
3439 break;
3440 case Instruction::SetNE:
3441 if (Max < RHSVal || Min > RHSVal)
3442 return ReplaceInstUsesWith(I, ConstantBool::True);
3443 break;
3444 case Instruction::SetLT:
3445 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3446 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3447 break;
3448 case Instruction::SetGT:
3449 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3450 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3451 break;
3452 }
3453 } else { // Signed comparison.
3454 int64_t Min, Max;
3455 int64_t RHSVal = CI->getSExtValue();
3456 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3457 Min, Max);
3458 switch (I.getOpcode()) { // LE/GE have been folded already.
3459 default: assert(0 && "Unknown setcc opcode!");
3460 case Instruction::SetEQ:
3461 if (Max < RHSVal || Min > RHSVal)
3462 return ReplaceInstUsesWith(I, ConstantBool::False);
3463 break;
3464 case Instruction::SetNE:
3465 if (Max < RHSVal || Min > RHSVal)
3466 return ReplaceInstUsesWith(I, ConstantBool::True);
3467 break;
3468 case Instruction::SetLT:
3469 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3470 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3471 break;
3472 case Instruction::SetGT:
3473 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3474 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3475 break;
3476 }
3477 }
3478 }
3479
3480
Chris Lattnere1e10e12004-05-25 06:32:08 +00003481 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003482 switch (LHSI->getOpcode()) {
3483 case Instruction::And:
3484 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3485 LHSI->getOperand(0)->hasOneUse()) {
3486 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3487 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3488 // happens a LOT in code produced by the C front-end, for bitfield
3489 // access.
3490 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003491 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3492
3493 // Check to see if there is a noop-cast between the shift and the and.
3494 if (!Shift) {
3495 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3496 if (CI->getOperand(0)->getType()->isIntegral() &&
3497 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3498 CI->getType()->getPrimitiveSizeInBits())
3499 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3500 }
3501
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003502 ConstantUInt *ShAmt;
3503 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003504 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3505 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003506
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003507 // We can fold this as long as we can't shift unknown bits
3508 // into the mask. This can only happen with signed shift
3509 // rights, as they sign-extend.
3510 if (ShAmt) {
3511 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003512 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003513 if (!CanFold) {
3514 // To test for the bad case of the signed shr, see if any
3515 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003516 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3517 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3518
3519 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003520 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003521 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3522 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003523 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3524 CanFold = true;
3525 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003526
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003527 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003528 Constant *NewCst;
3529 if (Shift->getOpcode() == Instruction::Shl)
3530 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3531 else
3532 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003533
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003534 // Check to see if we are shifting out any of the bits being
3535 // compared.
3536 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3537 // If we shifted bits out, the fold is not going to work out.
3538 // As a special case, check to see if this means that the
3539 // result is always true or false now.
3540 if (I.getOpcode() == Instruction::SetEQ)
3541 return ReplaceInstUsesWith(I, ConstantBool::False);
3542 if (I.getOpcode() == Instruction::SetNE)
3543 return ReplaceInstUsesWith(I, ConstantBool::True);
3544 } else {
3545 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003546 Constant *NewAndCST;
3547 if (Shift->getOpcode() == Instruction::Shl)
3548 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3549 else
3550 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3551 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003552 if (AndTy == Ty)
3553 LHSI->setOperand(0, Shift->getOperand(0));
3554 else {
3555 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3556 *Shift);
3557 LHSI->setOperand(0, NewCast);
3558 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003559 WorkList.push_back(Shift); // Shift is dead.
3560 AddUsesToWorkList(I);
3561 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003562 }
3563 }
Chris Lattner35167c32004-06-09 07:59:58 +00003564 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003565 }
3566 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003567
Chris Lattner272d5ca2004-09-28 18:22:15 +00003568 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3569 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3570 switch (I.getOpcode()) {
3571 default: break;
3572 case Instruction::SetEQ:
3573 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003574 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3575
3576 // Check that the shift amount is in range. If not, don't perform
3577 // undefined shifts. When the shift is visited it will be
3578 // simplified.
3579 if (ShAmt->getValue() >= TypeBits)
3580 break;
3581
Chris Lattner272d5ca2004-09-28 18:22:15 +00003582 // If we are comparing against bits always shifted out, the
3583 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003584 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003585 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3586 if (Comp != CI) {// Comparing against a bit that we know is zero.
3587 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3588 Constant *Cst = ConstantBool::get(IsSetNE);
3589 return ReplaceInstUsesWith(I, Cst);
3590 }
3591
3592 if (LHSI->hasOneUse()) {
3593 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003594 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003595 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3596
3597 Constant *Mask;
3598 if (CI->getType()->isUnsigned()) {
3599 Mask = ConstantUInt::get(CI->getType(), Val);
3600 } else if (ShAmtVal != 0) {
3601 Mask = ConstantSInt::get(CI->getType(), Val);
3602 } else {
3603 Mask = ConstantInt::getAllOnesValue(CI->getType());
3604 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003605
Chris Lattner272d5ca2004-09-28 18:22:15 +00003606 Instruction *AndI =
3607 BinaryOperator::createAnd(LHSI->getOperand(0),
3608 Mask, LHSI->getName()+".mask");
3609 Value *And = InsertNewInstBefore(AndI, I);
3610 return new SetCondInst(I.getOpcode(), And,
3611 ConstantExpr::getUShr(CI, ShAmt));
3612 }
3613 }
3614 }
3615 }
3616 break;
3617
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003618 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003619 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003620 switch (I.getOpcode()) {
3621 default: break;
3622 case Instruction::SetEQ:
3623 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003624
3625 // Check that the shift amount is in range. If not, don't perform
3626 // undefined shifts. When the shift is visited it will be
3627 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003628 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003629 if (ShAmt->getValue() >= TypeBits)
3630 break;
3631
Chris Lattner1023b872004-09-27 16:18:50 +00003632 // If we are comparing against bits always shifted out, the
3633 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003634 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003635 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003636
Chris Lattner1023b872004-09-27 16:18:50 +00003637 if (Comp != CI) {// Comparing against a bit that we know is zero.
3638 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3639 Constant *Cst = ConstantBool::get(IsSetNE);
3640 return ReplaceInstUsesWith(I, Cst);
3641 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003642
Chris Lattner1023b872004-09-27 16:18:50 +00003643 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003644 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003645
Chris Lattner1023b872004-09-27 16:18:50 +00003646 // Otherwise strength reduce the shift into an and.
3647 uint64_t Val = ~0ULL; // All ones.
3648 Val <<= ShAmtVal; // Shift over to the right spot.
3649
3650 Constant *Mask;
3651 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003652 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003653 Mask = ConstantUInt::get(CI->getType(), Val);
3654 } else {
3655 Mask = ConstantSInt::get(CI->getType(), Val);
3656 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003657
Chris Lattner1023b872004-09-27 16:18:50 +00003658 Instruction *AndI =
3659 BinaryOperator::createAnd(LHSI->getOperand(0),
3660 Mask, LHSI->getName()+".mask");
3661 Value *And = InsertNewInstBefore(AndI, I);
3662 return new SetCondInst(I.getOpcode(), And,
3663 ConstantExpr::getShl(CI, ShAmt));
3664 }
3665 break;
3666 }
3667 }
3668 }
3669 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003670
Chris Lattner6862fbd2004-09-29 17:40:11 +00003671 case Instruction::Div:
3672 // Fold: (div X, C1) op C2 -> range check
3673 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3674 // Fold this div into the comparison, producing a range check.
3675 // Determine, based on the divide type, what the range is being
3676 // checked. If there is an overflow on the low or high side, remember
3677 // it, otherwise compute the range [low, hi) bounding the new value.
3678 bool LoOverflow = false, HiOverflow = 0;
3679 ConstantInt *LoBound = 0, *HiBound = 0;
3680
3681 ConstantInt *Prod;
3682 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3683
Chris Lattnera92af962004-10-11 19:40:04 +00003684 Instruction::BinaryOps Opcode = I.getOpcode();
3685
Chris Lattner6862fbd2004-09-29 17:40:11 +00003686 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3687 } else if (LHSI->getType()->isUnsigned()) { // udiv
3688 LoBound = Prod;
3689 LoOverflow = ProdOV;
3690 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3691 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3692 if (CI->isNullValue()) { // (X / pos) op 0
3693 // Can't overflow.
3694 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3695 HiBound = DivRHS;
3696 } else if (isPositive(CI)) { // (X / pos) op pos
3697 LoBound = Prod;
3698 LoOverflow = ProdOV;
3699 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3700 } else { // (X / pos) op neg
3701 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3702 LoOverflow = AddWithOverflow(LoBound, Prod,
3703 cast<ConstantInt>(DivRHSH));
3704 HiBound = Prod;
3705 HiOverflow = ProdOV;
3706 }
3707 } else { // Divisor is < 0.
3708 if (CI->isNullValue()) { // (X / neg) op 0
3709 LoBound = AddOne(DivRHS);
3710 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003711 if (HiBound == DivRHS)
3712 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003713 } else if (isPositive(CI)) { // (X / neg) op pos
3714 HiOverflow = LoOverflow = ProdOV;
3715 if (!LoOverflow)
3716 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3717 HiBound = AddOne(Prod);
3718 } else { // (X / neg) op neg
3719 LoBound = Prod;
3720 LoOverflow = HiOverflow = ProdOV;
3721 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3722 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003723
Chris Lattnera92af962004-10-11 19:40:04 +00003724 // Dividing by a negate swaps the condition.
3725 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003726 }
3727
3728 if (LoBound) {
3729 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003730 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003731 default: assert(0 && "Unhandled setcc opcode!");
3732 case Instruction::SetEQ:
3733 if (LoOverflow && HiOverflow)
3734 return ReplaceInstUsesWith(I, ConstantBool::False);
3735 else if (HiOverflow)
3736 return new SetCondInst(Instruction::SetGE, X, LoBound);
3737 else if (LoOverflow)
3738 return new SetCondInst(Instruction::SetLT, X, HiBound);
3739 else
3740 return InsertRangeTest(X, LoBound, HiBound, true, I);
3741 case Instruction::SetNE:
3742 if (LoOverflow && HiOverflow)
3743 return ReplaceInstUsesWith(I, ConstantBool::True);
3744 else if (HiOverflow)
3745 return new SetCondInst(Instruction::SetLT, X, LoBound);
3746 else if (LoOverflow)
3747 return new SetCondInst(Instruction::SetGE, X, HiBound);
3748 else
3749 return InsertRangeTest(X, LoBound, HiBound, false, I);
3750 case Instruction::SetLT:
3751 if (LoOverflow)
3752 return ReplaceInstUsesWith(I, ConstantBool::False);
3753 return new SetCondInst(Instruction::SetLT, X, LoBound);
3754 case Instruction::SetGT:
3755 if (HiOverflow)
3756 return ReplaceInstUsesWith(I, ConstantBool::False);
3757 return new SetCondInst(Instruction::SetGE, X, HiBound);
3758 }
3759 }
3760 }
3761 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003762 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003763
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003764 // Simplify seteq and setne instructions...
3765 if (I.getOpcode() == Instruction::SetEQ ||
3766 I.getOpcode() == Instruction::SetNE) {
3767 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3768
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003769 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003770 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003771 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3772 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003773 case Instruction::Rem:
3774 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3775 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3776 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003777 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3778 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3779 if (isPowerOf2_64(V)) {
3780 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003781 const Type *UTy = BO->getType()->getUnsignedVersion();
3782 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3783 UTy, "tmp"), I);
3784 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3785 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3786 RHSCst, BO->getName()), I);
3787 return BinaryOperator::create(I.getOpcode(), NewRem,
3788 Constant::getNullValue(UTy));
3789 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003790 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003791 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003792
Chris Lattnerc992add2003-08-13 05:33:12 +00003793 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003794 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3795 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003796 if (BO->hasOneUse())
3797 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3798 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003799 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003800 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3801 // efficiently invertible, or if the add has just this one use.
3802 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003803
Chris Lattnerc992add2003-08-13 05:33:12 +00003804 if (Value *NegVal = dyn_castNegVal(BOp1))
3805 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3806 else if (Value *NegVal = dyn_castNegVal(BOp0))
3807 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003808 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003809 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3810 BO->setName("");
3811 InsertNewInstBefore(Neg, I);
3812 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3813 }
3814 }
3815 break;
3816 case Instruction::Xor:
3817 // For the xor case, we can xor two constants together, eliminating
3818 // the explicit xor.
3819 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3820 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003821 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003822
3823 // FALLTHROUGH
3824 case Instruction::Sub:
3825 // Replace (([sub|xor] A, B) != 0) with (A != B)
3826 if (CI->isNullValue())
3827 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3828 BO->getOperand(1));
3829 break;
3830
3831 case Instruction::Or:
3832 // If bits are being or'd in that are not present in the constant we
3833 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003834 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003835 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003836 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003837 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003838 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003839 break;
3840
3841 case Instruction::And:
3842 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003843 // If bits are being compared against that are and'd out, then the
3844 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003845 if (!ConstantExpr::getAnd(CI,
3846 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003847 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003848
Chris Lattner35167c32004-06-09 07:59:58 +00003849 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003850 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003851 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3852 Instruction::SetNE, Op0,
3853 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003854
Chris Lattnerc992add2003-08-13 05:33:12 +00003855 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3856 // to be a signed value as appropriate.
3857 if (isSignBit(BOC)) {
3858 Value *X = BO->getOperand(0);
3859 // If 'X' is not signed, insert a cast now...
3860 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003861 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003862 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003863 }
3864 return new SetCondInst(isSetNE ? Instruction::SetLT :
3865 Instruction::SetGE, X,
3866 Constant::getNullValue(X->getType()));
3867 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003868
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003869 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003870 if (CI->isNullValue() && isHighOnes(BOC)) {
3871 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003872 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003873
3874 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003875 if (NegX->getType()->isSigned()) {
3876 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3877 X = InsertCastBefore(X, DestTy, I);
3878 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003879 }
3880
3881 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003882 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003883 }
3884
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003885 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003886 default: break;
3887 }
3888 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003889 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003890 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003891 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3892 Value *CastOp = Cast->getOperand(0);
3893 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003894 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003895 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003896 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003897 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003898 "Source and destination signednesses should differ!");
3899 if (Cast->getType()->isSigned()) {
3900 // If this is a signed comparison, check for comparisons in the
3901 // vicinity of zero.
3902 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3903 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003904 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003905 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003906 else if (I.getOpcode() == Instruction::SetGT &&
3907 cast<ConstantSInt>(CI)->getValue() == -1)
3908 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003909 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003910 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003911 } else {
3912 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3913 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003914 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003915 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003916 return BinaryOperator::createSetGT(CastOp,
3917 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003918 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003919 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003920 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003921 return BinaryOperator::createSetLT(CastOp,
3922 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003923 }
3924 }
3925 }
Chris Lattnere967b342003-06-04 05:10:11 +00003926 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003927 }
3928
Chris Lattner77c32c32005-04-23 15:31:55 +00003929 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3930 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3931 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3932 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003933 case Instruction::GetElementPtr:
3934 if (RHSC->isNullValue()) {
3935 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3936 bool isAllZeros = true;
3937 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3938 if (!isa<Constant>(LHSI->getOperand(i)) ||
3939 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3940 isAllZeros = false;
3941 break;
3942 }
3943 if (isAllZeros)
3944 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3945 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3946 }
3947 break;
3948
Chris Lattner77c32c32005-04-23 15:31:55 +00003949 case Instruction::PHI:
3950 if (Instruction *NV = FoldOpIntoPhi(I))
3951 return NV;
3952 break;
3953 case Instruction::Select:
3954 // If either operand of the select is a constant, we can fold the
3955 // comparison into the select arms, which will cause one to be
3956 // constant folded and the select turned into a bitwise or.
3957 Value *Op1 = 0, *Op2 = 0;
3958 if (LHSI->hasOneUse()) {
3959 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3960 // Fold the known value into the constant operand.
3961 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3962 // Insert a new SetCC of the other select operand.
3963 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3964 LHSI->getOperand(2), RHSC,
3965 I.getName()), I);
3966 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3967 // Fold the known value into the constant operand.
3968 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3969 // Insert a new SetCC of the other select operand.
3970 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3971 LHSI->getOperand(1), RHSC,
3972 I.getName()), I);
3973 }
3974 }
Jeff Cohen82639852005-04-23 21:38:35 +00003975
Chris Lattner77c32c32005-04-23 15:31:55 +00003976 if (Op1)
3977 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3978 break;
3979 }
3980 }
3981
Chris Lattner0798af32005-01-13 20:14:25 +00003982 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3983 if (User *GEP = dyn_castGetElementPtr(Op0))
3984 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3985 return NI;
3986 if (User *GEP = dyn_castGetElementPtr(Op1))
3987 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3988 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3989 return NI;
3990
Chris Lattner16930792003-11-03 04:25:02 +00003991 // Test to see if the operands of the setcc are casted versions of other
3992 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003993 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3994 Value *CastOp0 = CI->getOperand(0);
3995 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003996 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003997 (I.getOpcode() == Instruction::SetEQ ||
3998 I.getOpcode() == Instruction::SetNE)) {
3999 // We keep moving the cast from the left operand over to the right
4000 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004001 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004002
Chris Lattner16930792003-11-03 04:25:02 +00004003 // If operand #1 is a cast instruction, see if we can eliminate it as
4004 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004005 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4006 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004007 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004008 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004009
Chris Lattner16930792003-11-03 04:25:02 +00004010 // If Op1 is a constant, we can fold the cast into the constant.
4011 if (Op1->getType() != Op0->getType())
4012 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4013 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4014 } else {
4015 // Otherwise, cast the RHS right before the setcc
4016 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4017 InsertNewInstBefore(cast<Instruction>(Op1), I);
4018 }
4019 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4020 }
4021
Chris Lattner6444c372003-11-03 05:17:03 +00004022 // Handle the special case of: setcc (cast bool to X), <cst>
4023 // This comes up when you have code like
4024 // int X = A < B;
4025 // if (X) ...
4026 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004027 // with a constant or another cast from the same type.
4028 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4029 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4030 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004031 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004032
4033 if (I.getOpcode() == Instruction::SetNE ||
4034 I.getOpcode() == Instruction::SetEQ) {
4035 Value *A, *B;
4036 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4037 (A == Op1 || B == Op1)) {
4038 // (A^B) == A -> B == 0
4039 Value *OtherVal = A == Op1 ? B : A;
4040 return BinaryOperator::create(I.getOpcode(), OtherVal,
4041 Constant::getNullValue(A->getType()));
4042 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4043 (A == Op0 || B == Op0)) {
4044 // A == (A^B) -> B == 0
4045 Value *OtherVal = A == Op0 ? B : A;
4046 return BinaryOperator::create(I.getOpcode(), OtherVal,
4047 Constant::getNullValue(A->getType()));
4048 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4049 // (A-B) == A -> B == 0
4050 return BinaryOperator::create(I.getOpcode(), B,
4051 Constant::getNullValue(B->getType()));
4052 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4053 // A == (A-B) -> B == 0
4054 return BinaryOperator::create(I.getOpcode(), B,
4055 Constant::getNullValue(B->getType()));
4056 }
4057 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004058 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004059}
4060
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004061// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4062// We only handle extending casts so far.
4063//
4064Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4065 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4066 const Type *SrcTy = LHSCIOp->getType();
4067 const Type *DestTy = SCI.getOperand(0)->getType();
4068 Value *RHSCIOp;
4069
4070 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004071 return 0;
4072
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004073 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4074 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4075 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4076
4077 // Is this a sign or zero extension?
4078 bool isSignSrc = SrcTy->isSigned();
4079 bool isSignDest = DestTy->isSigned();
4080
4081 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4082 // Not an extension from the same type?
4083 RHSCIOp = CI->getOperand(0);
4084 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4085 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4086 // Compute the constant that would happen if we truncated to SrcTy then
4087 // reextended to DestTy.
4088 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4089
4090 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4091 RHSCIOp = Res;
4092 } else {
4093 // If the value cannot be represented in the shorter type, we cannot emit
4094 // a simple comparison.
4095 if (SCI.getOpcode() == Instruction::SetEQ)
4096 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4097 if (SCI.getOpcode() == Instruction::SetNE)
4098 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4099
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004100 // Evaluate the comparison for LT.
4101 Value *Result;
4102 if (DestTy->isSigned()) {
4103 // We're performing a signed comparison.
4104 if (isSignSrc) {
4105 // Signed extend and signed comparison.
4106 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4107 Result = ConstantBool::False;
4108 else
4109 Result = ConstantBool::True; // X < (large) --> true
4110 } else {
4111 // Unsigned extend and signed comparison.
4112 if (cast<ConstantSInt>(CI)->getValue() < 0)
4113 Result = ConstantBool::False;
4114 else
4115 Result = ConstantBool::True;
4116 }
4117 } else {
4118 // We're performing an unsigned comparison.
4119 if (!isSignSrc) {
4120 // Unsigned extend & compare -> always true.
4121 Result = ConstantBool::True;
4122 } else {
4123 // We're performing an unsigned comp with a sign extended value.
4124 // This is true if the input is >= 0. [aka >s -1]
4125 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4126 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4127 NegOne, SCI.getName()), SCI);
4128 }
Reid Spencer279fa252004-11-28 21:31:15 +00004129 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004130
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004131 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004132 if (SCI.getOpcode() == Instruction::SetLT) {
4133 return ReplaceInstUsesWith(SCI, Result);
4134 } else {
4135 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4136 if (Constant *CI = dyn_cast<Constant>(Result))
4137 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4138 else
4139 return BinaryOperator::createNot(Result);
4140 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004141 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004142 } else {
4143 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004144 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004145
Chris Lattner252a8452005-06-16 03:00:08 +00004146 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004147 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4148}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004149
Chris Lattnere8d6c602003-03-10 19:16:08 +00004150Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004151 assert(I.getOperand(1)->getType() == Type::UByteTy);
4152 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004153 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004154
4155 // shl X, 0 == X and shr X, 0 == X
4156 // shl 0, X == 0 and shr 0, X == 0
4157 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004158 Op0 == Constant::getNullValue(Op0->getType()))
4159 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004160
Chris Lattner81a7a232004-10-16 18:11:37 +00004161 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4162 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004163 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004164 else // undef << X -> 0 AND undef >>u X -> 0
4165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4166 }
4167 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004168 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004169 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4170 else
4171 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4172 }
4173
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004174 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4175 if (!isLeftShift)
4176 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4177 if (CSI->isAllOnesValue())
4178 return ReplaceInstUsesWith(I, CSI);
4179
Chris Lattner183b3362004-04-09 19:05:30 +00004180 // Try to fold constant and into select arguments.
4181 if (isa<Constant>(Op0))
4182 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004183 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004184 return R;
4185
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004186 // See if we can turn a signed shr into an unsigned shr.
4187 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004188 if (MaskedValueIsZero(Op0,
4189 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004190 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4191 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4192 I.getName()), I);
4193 return new CastInst(V, I.getType());
4194 }
4195 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004196
Chris Lattner14553932006-01-06 07:12:35 +00004197 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4198 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4199 return Res;
4200 return 0;
4201}
4202
4203Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4204 ShiftInst &I) {
4205 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004206 bool isSignedShift = Op0->getType()->isSigned();
4207 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004208
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004209 // See if we can simplify any instructions used by the instruction whose sole
4210 // purpose is to compute bits we don't care about.
4211 uint64_t KnownZero, KnownOne;
4212 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4213 KnownZero, KnownOne))
4214 return &I;
4215
Chris Lattner14553932006-01-06 07:12:35 +00004216 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4217 // of a signed value.
4218 //
4219 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4220 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004221 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004222 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4223 else {
4224 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4225 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004226 }
Chris Lattner14553932006-01-06 07:12:35 +00004227 }
4228
4229 // ((X*C1) << C2) == (X * (C1 << C2))
4230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4231 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4232 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4233 return BinaryOperator::createMul(BO->getOperand(0),
4234 ConstantExpr::getShl(BOOp, Op1));
4235
4236 // Try to fold constant and into select arguments.
4237 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4238 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4239 return R;
4240 if (isa<PHINode>(Op0))
4241 if (Instruction *NV = FoldOpIntoPhi(I))
4242 return NV;
4243
4244 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004245 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4246 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4247 Value *V1, *V2;
4248 ConstantInt *CC;
4249 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004250 default: break;
4251 case Instruction::Add:
4252 case Instruction::And:
4253 case Instruction::Or:
4254 case Instruction::Xor:
4255 // These operators commute.
4256 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004257 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4258 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004259 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004260 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004261 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004262 Op0BO->getName());
4263 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004264 Instruction *X =
4265 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4266 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004267 InsertNewInstBefore(X, I); // (X + (Y << C))
4268 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004269 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004270 return BinaryOperator::createAnd(X, C2);
4271 }
Chris Lattner14553932006-01-06 07:12:35 +00004272
Chris Lattner797dee72005-09-18 06:30:59 +00004273 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4274 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4275 match(Op0BO->getOperand(1),
4276 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004277 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004278 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004279 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004280 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004281 Op0BO->getName());
4282 InsertNewInstBefore(YS, I); // (Y << C)
4283 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004284 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004285 V1->getName()+".mask");
4286 InsertNewInstBefore(XM, I); // X & (CC << C)
4287
4288 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4289 }
Chris Lattner14553932006-01-06 07:12:35 +00004290
Chris Lattner797dee72005-09-18 06:30:59 +00004291 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004292 case Instruction::Sub:
4293 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004294 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4295 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004296 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004297 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004298 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004299 Op0BO->getName());
4300 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004301 Instruction *X =
4302 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4303 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004304 InsertNewInstBefore(X, I); // (X + (Y << C))
4305 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004306 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004307 return BinaryOperator::createAnd(X, C2);
4308 }
Chris Lattner14553932006-01-06 07:12:35 +00004309
Chris Lattner797dee72005-09-18 06:30:59 +00004310 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4311 match(Op0BO->getOperand(0),
4312 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004313 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004314 cast<BinaryOperator>(Op0BO->getOperand(0))
4315 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004316 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004317 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004318 Op0BO->getName());
4319 InsertNewInstBefore(YS, I); // (Y << C)
4320 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004321 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004322 V1->getName()+".mask");
4323 InsertNewInstBefore(XM, I); // X & (CC << C)
4324
4325 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4326 }
Chris Lattner14553932006-01-06 07:12:35 +00004327
Chris Lattner27cb9db2005-09-18 05:12:10 +00004328 break;
Chris Lattner14553932006-01-06 07:12:35 +00004329 }
4330
4331
4332 // If the operand is an bitwise operator with a constant RHS, and the
4333 // shift is the only use, we can pull it out of the shift.
4334 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4335 bool isValid = true; // Valid only for And, Or, Xor
4336 bool highBitSet = false; // Transform if high bit of constant set?
4337
4338 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004339 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004340 case Instruction::Add:
4341 isValid = isLeftShift;
4342 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004343 case Instruction::Or:
4344 case Instruction::Xor:
4345 highBitSet = false;
4346 break;
4347 case Instruction::And:
4348 highBitSet = true;
4349 break;
Chris Lattner14553932006-01-06 07:12:35 +00004350 }
4351
4352 // If this is a signed shift right, and the high bit is modified
4353 // by the logical operation, do not perform the transformation.
4354 // The highBitSet boolean indicates the value of the high bit of
4355 // the constant which would cause it to be modified for this
4356 // operation.
4357 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004358 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004359 uint64_t Val = Op0C->getRawValue();
4360 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4361 }
4362
4363 if (isValid) {
4364 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4365
4366 Instruction *NewShift =
4367 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4368 Op0BO->getName());
4369 Op0BO->setName("");
4370 InsertNewInstBefore(NewShift, I);
4371
4372 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4373 NewRHS);
4374 }
4375 }
4376 }
4377 }
4378
Chris Lattnereb372a02006-01-06 07:52:12 +00004379 // Find out if this is a shift of a shift by a constant.
4380 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004381 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004382 ShiftOp = Op0SI;
4383 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4384 // If this is a noop-integer case of a shift instruction, use the shift.
4385 if (CI->getOperand(0)->getType()->isInteger() &&
4386 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4387 CI->getType()->getPrimitiveSizeInBits() &&
4388 isa<ShiftInst>(CI->getOperand(0))) {
4389 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4390 }
4391 }
4392
4393 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4394 // Find the operands and properties of the input shift. Note that the
4395 // signedness of the input shift may differ from the current shift if there
4396 // is a noop cast between the two.
4397 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4398 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004399 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004400
4401 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4402
4403 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4404 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4405
4406 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4407 if (isLeftShift == isShiftOfLeftShift) {
4408 // Do not fold these shifts if the first one is signed and the second one
4409 // is unsigned and this is a right shift. Further, don't do any folding
4410 // on them.
4411 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4412 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004413
Chris Lattnereb372a02006-01-06 07:52:12 +00004414 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4415 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4416 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004417
Chris Lattnereb372a02006-01-06 07:52:12 +00004418 Value *Op = ShiftOp->getOperand(0);
4419 if (isShiftOfSignedShift != isSignedShift)
4420 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4421 return new ShiftInst(I.getOpcode(), Op,
4422 ConstantUInt::get(Type::UByteTy, Amt));
4423 }
4424
4425 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4426 // signed types, we can only support the (A >> c1) << c2 configuration,
4427 // because it can not turn an arbitrary bit of A into a sign bit.
4428 if (isUnsignedShift || isLeftShift) {
4429 // Calculate bitmask for what gets shifted off the edge.
4430 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4431 if (isLeftShift)
4432 C = ConstantExpr::getShl(C, ShiftAmt1C);
4433 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004434 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004435
4436 Value *Op = ShiftOp->getOperand(0);
4437 if (isShiftOfSignedShift != isSignedShift)
4438 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4439
4440 Instruction *Mask =
4441 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4442 InsertNewInstBefore(Mask, I);
4443
4444 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004445 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004446 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004447 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004448 return new ShiftInst(I.getOpcode(), Mask,
4449 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004450 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4451 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4452 // Make sure to emit an unsigned shift right, not a signed one.
4453 Mask = InsertNewInstBefore(new CastInst(Mask,
4454 Mask->getType()->getUnsignedVersion(),
4455 Op->getName()), I);
4456 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004457 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004458 InsertNewInstBefore(Mask, I);
4459 return new CastInst(Mask, I.getType());
4460 } else {
4461 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4462 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4463 }
4464 } else {
4465 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4466 Op = InsertNewInstBefore(new CastInst(Mask,
4467 I.getType()->getSignedVersion(),
4468 Mask->getName()), I);
4469 Instruction *Shift =
4470 new ShiftInst(ShiftOp->getOpcode(), Op,
4471 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4472 InsertNewInstBefore(Shift, I);
4473
4474 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4475 C = ConstantExpr::getShl(C, Op1);
4476 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4477 InsertNewInstBefore(Mask, I);
4478 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004479 }
4480 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004481 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004482 // this case, C1 == C2 and C1 is 8, 16, or 32.
4483 if (ShiftAmt1 == ShiftAmt2) {
4484 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004485 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004486 case 8 : SExtType = Type::SByteTy; break;
4487 case 16: SExtType = Type::ShortTy; break;
4488 case 32: SExtType = Type::IntTy; break;
4489 }
4490
4491 if (SExtType) {
4492 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4493 SExtType, "sext");
4494 InsertNewInstBefore(NewTrunc, I);
4495 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004496 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004497 }
Chris Lattner86102b82005-01-01 16:22:27 +00004498 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004499 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004500 return 0;
4501}
4502
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004503enum CastType {
4504 Noop = 0,
4505 Truncate = 1,
4506 Signext = 2,
4507 Zeroext = 3
4508};
4509
4510/// getCastType - In the future, we will split the cast instruction into these
4511/// various types. Until then, we have to do the analysis here.
4512static CastType getCastType(const Type *Src, const Type *Dest) {
4513 assert(Src->isIntegral() && Dest->isIntegral() &&
4514 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004515 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4516 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004517
4518 if (SrcSize == DestSize) return Noop;
4519 if (SrcSize > DestSize) return Truncate;
4520 if (Src->isSigned()) return Signext;
4521 return Zeroext;
4522}
4523
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004524
Chris Lattner48a44f72002-05-02 17:06:02 +00004525// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4526// instruction.
4527//
Chris Lattnere154abf2006-01-19 07:40:22 +00004528static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4529 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004530
Chris Lattner650b6da2002-08-02 20:00:25 +00004531 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004532 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004533 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004534 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004535 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004536
Chris Lattner4fbad962004-07-21 04:27:24 +00004537 // If we are casting between pointer and integer types, treat pointers as
4538 // integers of the appropriate size for the code below.
4539 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4540 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4541 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004542
Chris Lattner48a44f72002-05-02 17:06:02 +00004543 // Allow free casting and conversion of sizes as long as the sign doesn't
4544 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004545 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004546 CastType FirstCast = getCastType(SrcTy, MidTy);
4547 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004548
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004549 // Capture the effect of these two casts. If the result is a legal cast,
4550 // the CastType is stored here, otherwise a special code is used.
4551 static const unsigned CastResult[] = {
4552 // First cast is noop
4553 0, 1, 2, 3,
4554 // First cast is a truncate
4555 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4556 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004557 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004558 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004559 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004560 };
4561
4562 unsigned Result = CastResult[FirstCast*4+SecondCast];
4563 switch (Result) {
4564 default: assert(0 && "Illegal table value!");
4565 case 0:
4566 case 1:
4567 case 2:
4568 case 3:
4569 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4570 // truncates, we could eliminate more casts.
4571 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4572 case 4:
4573 return false; // Not possible to eliminate this here.
4574 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004575 // Sign or zero extend followed by truncate is always ok if the result
4576 // is a truncate or noop.
4577 CastType ResultCast = getCastType(SrcTy, DstTy);
4578 if (ResultCast == Noop || ResultCast == Truncate)
4579 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004580 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004581 // result will match the sign/zeroextendness of the result.
4582 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004583 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004584 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004585
4586 // If this is a cast from 'float -> double -> integer', cast from
4587 // 'float -> integer' directly, as the value isn't changed by the
4588 // float->double conversion.
4589 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4590 DstTy->isIntegral() &&
4591 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4592 return true;
4593
Chris Lattnercaba72b2006-04-02 05:43:13 +00004594 // Packed type conversions don't modify bits.
4595 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
4596 return true;
4597
Chris Lattner48a44f72002-05-02 17:06:02 +00004598 return false;
4599}
4600
Chris Lattner11ffd592004-07-20 05:21:00 +00004601static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004602 if (V->getType() == Ty || isa<Constant>(V)) return false;
4603 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004604 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4605 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004606 return false;
4607 return true;
4608}
4609
4610/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4611/// InsertBefore instruction. This is specialized a bit to avoid inserting
4612/// casts that are known to not do anything...
4613///
4614Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4615 Instruction *InsertBefore) {
4616 if (V->getType() == DestTy) return V;
4617 if (Constant *C = dyn_cast<Constant>(V))
4618 return ConstantExpr::getCast(C, DestTy);
4619
4620 CastInst *CI = new CastInst(V, DestTy, V->getName());
4621 InsertNewInstBefore(CI, *InsertBefore);
4622 return CI;
4623}
Chris Lattner48a44f72002-05-02 17:06:02 +00004624
Chris Lattner8f663e82005-10-29 04:36:15 +00004625/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4626/// expression. If so, decompose it, returning some value X, such that Val is
4627/// X*Scale+Offset.
4628///
4629static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4630 unsigned &Offset) {
4631 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4632 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4633 Offset = CI->getValue();
4634 Scale = 1;
4635 return ConstantUInt::get(Type::UIntTy, 0);
4636 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4637 if (I->getNumOperands() == 2) {
4638 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4639 if (I->getOpcode() == Instruction::Shl) {
4640 // This is a value scaled by '1 << the shift amt'.
4641 Scale = 1U << CUI->getValue();
4642 Offset = 0;
4643 return I->getOperand(0);
4644 } else if (I->getOpcode() == Instruction::Mul) {
4645 // This value is scaled by 'CUI'.
4646 Scale = CUI->getValue();
4647 Offset = 0;
4648 return I->getOperand(0);
4649 } else if (I->getOpcode() == Instruction::Add) {
4650 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4651 // divisible by C2.
4652 unsigned SubScale;
4653 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4654 Offset);
4655 Offset += CUI->getValue();
4656 if (SubScale > 1 && (Offset % SubScale == 0)) {
4657 Scale = SubScale;
4658 return SubVal;
4659 }
4660 }
4661 }
4662 }
4663 }
4664
4665 // Otherwise, we can't look past this.
4666 Scale = 1;
4667 Offset = 0;
4668 return Val;
4669}
4670
4671
Chris Lattner216be912005-10-24 06:03:58 +00004672/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4673/// try to eliminate the cast by moving the type information into the alloc.
4674Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4675 AllocationInst &AI) {
4676 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004677 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004678
Chris Lattnerac87beb2005-10-24 06:22:12 +00004679 // Remove any uses of AI that are dead.
4680 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4681 std::vector<Instruction*> DeadUsers;
4682 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4683 Instruction *User = cast<Instruction>(*UI++);
4684 if (isInstructionTriviallyDead(User)) {
4685 while (UI != E && *UI == User)
4686 ++UI; // If this instruction uses AI more than once, don't break UI.
4687
4688 // Add operands to the worklist.
4689 AddUsesToWorkList(*User);
4690 ++NumDeadInst;
4691 DEBUG(std::cerr << "IC: DCE: " << *User);
4692
4693 User->eraseFromParent();
4694 removeFromWorkList(User);
4695 }
4696 }
4697
Chris Lattner216be912005-10-24 06:03:58 +00004698 // Get the type really allocated and the type casted to.
4699 const Type *AllocElTy = AI.getAllocatedType();
4700 const Type *CastElTy = PTy->getElementType();
4701 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004702
4703 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4704 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4705 if (CastElTyAlign < AllocElTyAlign) return 0;
4706
Chris Lattner46705b22005-10-24 06:35:18 +00004707 // If the allocation has multiple uses, only promote it if we are strictly
4708 // increasing the alignment of the resultant allocation. If we keep it the
4709 // same, we open the door to infinite loops of various kinds.
4710 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4711
Chris Lattner216be912005-10-24 06:03:58 +00004712 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4713 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004714 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004715
Chris Lattner8270c332005-10-29 03:19:53 +00004716 // See if we can satisfy the modulus by pulling a scale out of the array
4717 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004718 unsigned ArraySizeScale, ArrayOffset;
4719 Value *NumElements = // See if the array size is a decomposable linear expr.
4720 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4721
Chris Lattner8270c332005-10-29 03:19:53 +00004722 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4723 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004724 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4725 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004726
Chris Lattner8270c332005-10-29 03:19:53 +00004727 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4728 Value *Amt = 0;
4729 if (Scale == 1) {
4730 Amt = NumElements;
4731 } else {
4732 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4733 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4734 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4735 else if (Scale != 1) {
4736 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4737 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004738 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004739 }
4740
Chris Lattner8f663e82005-10-29 04:36:15 +00004741 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4742 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4743 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4744 Amt = InsertNewInstBefore(Tmp, AI);
4745 }
4746
Chris Lattner216be912005-10-24 06:03:58 +00004747 std::string Name = AI.getName(); AI.setName("");
4748 AllocationInst *New;
4749 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004750 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004751 else
Nate Begeman848622f2005-11-05 09:21:28 +00004752 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004753 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004754
4755 // If the allocation has multiple uses, insert a cast and change all things
4756 // that used it to use the new cast. This will also hack on CI, but it will
4757 // die soon.
4758 if (!AI.hasOneUse()) {
4759 AddUsesToWorkList(AI);
4760 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4761 InsertNewInstBefore(NewCast, AI);
4762 AI.replaceAllUsesWith(NewCast);
4763 }
Chris Lattner216be912005-10-24 06:03:58 +00004764 return ReplaceInstUsesWith(CI, New);
4765}
4766
4767
Chris Lattner48a44f72002-05-02 17:06:02 +00004768// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004769//
Chris Lattner113f4f42002-06-25 16:13:24 +00004770Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004771 Value *Src = CI.getOperand(0);
4772
Chris Lattner48a44f72002-05-02 17:06:02 +00004773 // If the user is casting a value to the same type, eliminate this cast
4774 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004775 if (CI.getType() == Src->getType())
4776 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004777
Chris Lattner81a7a232004-10-16 18:11:37 +00004778 if (isa<UndefValue>(Src)) // cast undef -> undef
4779 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4780
Chris Lattner48a44f72002-05-02 17:06:02 +00004781 // If casting the result of another cast instruction, try to eliminate this
4782 // one!
4783 //
Chris Lattner86102b82005-01-01 16:22:27 +00004784 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4785 Value *A = CSrc->getOperand(0);
4786 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4787 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004788 // This instruction now refers directly to the cast's src operand. This
4789 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004790 CI.setOperand(0, CSrc->getOperand(0));
4791 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004792 }
4793
Chris Lattner650b6da2002-08-02 20:00:25 +00004794 // If this is an A->B->A cast, and we are dealing with integral types, try
4795 // to convert this into a logical 'and' instruction.
4796 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004797 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004798 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004799 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004800 CSrc->getType()->getPrimitiveSizeInBits() <
4801 CI.getType()->getPrimitiveSizeInBits()&&
4802 A->getType()->getPrimitiveSizeInBits() ==
4803 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004804 assert(CSrc->getType() != Type::ULongTy &&
4805 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004806 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004807 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4808 AndValue);
4809 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4810 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4811 if (And->getType() != CI.getType()) {
4812 And->setName(CSrc->getName()+".mask");
4813 InsertNewInstBefore(And, CI);
4814 And = new CastInst(And, CI.getType());
4815 }
4816 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004817 }
4818 }
Chris Lattner2590e512006-02-07 06:56:34 +00004819
Chris Lattner03841652004-05-25 04:29:21 +00004820 // If this is a cast to bool, turn it into the appropriate setne instruction.
4821 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004822 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004823 Constant::getNullValue(CI.getOperand(0)->getType()));
4824
Chris Lattner2590e512006-02-07 06:56:34 +00004825 // See if we can simplify any instructions used by the LHS whose sole
4826 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004827 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4828 uint64_t KnownZero, KnownOne;
4829 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4830 KnownZero, KnownOne))
4831 return &CI;
4832 }
Chris Lattner2590e512006-02-07 06:56:34 +00004833
Chris Lattnerd0d51602003-06-21 23:12:02 +00004834 // If casting the result of a getelementptr instruction with no offset, turn
4835 // this into a cast of the original pointer!
4836 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004837 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004838 bool AllZeroOperands = true;
4839 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4840 if (!isa<Constant>(GEP->getOperand(i)) ||
4841 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4842 AllZeroOperands = false;
4843 break;
4844 }
4845 if (AllZeroOperands) {
4846 CI.setOperand(0, GEP->getOperand(0));
4847 return &CI;
4848 }
4849 }
4850
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004851 // If we are casting a malloc or alloca to a pointer to a type of the same
4852 // size, rewrite the allocation instruction to allocate the "right" type.
4853 //
4854 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004855 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4856 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004857
Chris Lattner86102b82005-01-01 16:22:27 +00004858 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4859 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4860 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004861 if (isa<PHINode>(Src))
4862 if (Instruction *NV = FoldOpIntoPhi(CI))
4863 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00004864
4865 // If the source and destination are pointers, and this cast is equivalent to
4866 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4867 // This can enhance SROA and other transforms that want type-safe pointers.
4868 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4869 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4870 const Type *DstTy = DstPTy->getElementType();
4871 const Type *SrcTy = SrcPTy->getElementType();
4872
4873 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4874 unsigned NumZeros = 0;
4875 while (SrcTy != DstTy &&
4876 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4877 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4878 ++NumZeros;
4879 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004880
Chris Lattnerb19a5c62006-04-12 18:09:35 +00004881 // If we found a path from the src to dest, create the getelementptr now.
4882 if (SrcTy == DstTy) {
4883 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4884 return new GetElementPtrInst(Src, Idxs);
4885 }
4886 }
4887
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004888 // If the source value is an instruction with only this use, we can attempt to
4889 // propagate the cast into the instruction. Also, only handle integral types
4890 // for now.
4891 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004892 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004893 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4894 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004895 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4896 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004897
4898 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4899 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4900
4901 switch (SrcI->getOpcode()) {
4902 case Instruction::Add:
4903 case Instruction::Mul:
4904 case Instruction::And:
4905 case Instruction::Or:
4906 case Instruction::Xor:
4907 // If we are discarding information, or just changing the sign, rewrite.
4908 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4909 // Don't insert two casts if they cannot be eliminated. We allow two
4910 // casts to be inserted if the sizes are the same. This could only be
4911 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004912 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4913 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004914 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4915 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4916 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4917 ->getOpcode(), Op0c, Op1c);
4918 }
4919 }
Chris Lattner72086162005-05-06 02:07:39 +00004920
4921 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4922 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4923 Op1 == ConstantBool::True &&
4924 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4925 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4926 return BinaryOperator::createXor(New,
4927 ConstantInt::get(CI.getType(), 1));
4928 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004929 break;
4930 case Instruction::Shl:
4931 // Allow changing the sign of the source operand. Do not allow changing
4932 // the size of the shift, UNLESS the shift amount is a constant. We
4933 // mush not change variable sized shifts to a smaller size, because it
4934 // is undefined to shift more bits out than exist in the value.
4935 if (DestBitSize == SrcBitSize ||
4936 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4937 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4938 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4939 }
4940 break;
Chris Lattner87380412005-05-06 04:18:52 +00004941 case Instruction::Shr:
4942 // If this is a signed shr, and if all bits shifted in are about to be
4943 // truncated off, turn it into an unsigned shr to allow greater
4944 // simplifications.
4945 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4946 isa<ConstantInt>(Op1)) {
4947 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4948 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4949 // Convert to unsigned.
4950 Value *N1 = InsertOperandCastBefore(Op0,
4951 Op0->getType()->getUnsignedVersion(), &CI);
4952 // Insert the new shift, which is now unsigned.
4953 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4954 Op1, Src->getName()), CI);
4955 return new CastInst(N1, CI.getType());
4956 }
4957 }
4958 break;
4959
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004960 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00004961 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004962 // We if we are just checking for a seteq of a single bit and casting it
4963 // to an integer. If so, shift the bit to the appropriate place then
4964 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00004965 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004966 uint64_t Op1CV = Op1C->getZExtValue();
4967 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4968 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4969 // cast (X == 1) to int --> X iff X has only the low bit set.
4970 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4971 // cast (X != 0) to int --> X iff X has only the low bit set.
4972 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4973 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4974 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4975 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4976 // If Op1C some other power of two, convert:
4977 uint64_t KnownZero, KnownOne;
4978 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4979 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4980
4981 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4982 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4983 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4984 // (X&4) == 2 --> false
4985 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00004986 Constant *Res = ConstantBool::get(isSetNE);
4987 Res = ConstantExpr::getCast(Res, CI.getType());
4988 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004989 }
4990
4991 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4992 Value *In = Op0;
4993 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004994 // Perform an unsigned shr by shiftamt. Convert input to
4995 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00004996 if (In->getType()->isSigned())
4997 In = InsertNewInstBefore(new CastInst(In,
4998 In->getType()->getUnsignedVersion(), In->getName()),CI);
4999 // Insert the shift to put the result in the low bit.
5000 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005001 ConstantInt::get(Type::UByteTy, ShiftAmt),
5002 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005003 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005004
5005 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5006 Constant *One = ConstantInt::get(In->getType(), 1);
5007 In = BinaryOperator::createXor(In, One, "tmp");
5008 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005009 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005010
5011 if (CI.getType() == In->getType())
5012 return ReplaceInstUsesWith(CI, In);
5013 else
5014 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005015 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005016 }
5017 }
5018 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005019 }
5020 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005021
Chris Lattner260ab202002-04-18 17:39:14 +00005022 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005023}
5024
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005025/// GetSelectFoldableOperands - We want to turn code that looks like this:
5026/// %C = or %A, %B
5027/// %D = select %cond, %C, %A
5028/// into:
5029/// %C = select %cond, %B, 0
5030/// %D = or %A, %C
5031///
5032/// Assuming that the specified instruction is an operand to the select, return
5033/// a bitmask indicating which operands of this instruction are foldable if they
5034/// equal the other incoming value of the select.
5035///
5036static unsigned GetSelectFoldableOperands(Instruction *I) {
5037 switch (I->getOpcode()) {
5038 case Instruction::Add:
5039 case Instruction::Mul:
5040 case Instruction::And:
5041 case Instruction::Or:
5042 case Instruction::Xor:
5043 return 3; // Can fold through either operand.
5044 case Instruction::Sub: // Can only fold on the amount subtracted.
5045 case Instruction::Shl: // Can only fold on the shift amount.
5046 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005047 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005048 default:
5049 return 0; // Cannot fold
5050 }
5051}
5052
5053/// GetSelectFoldableConstant - For the same transformation as the previous
5054/// function, return the identity constant that goes into the select.
5055static Constant *GetSelectFoldableConstant(Instruction *I) {
5056 switch (I->getOpcode()) {
5057 default: assert(0 && "This cannot happen!"); abort();
5058 case Instruction::Add:
5059 case Instruction::Sub:
5060 case Instruction::Or:
5061 case Instruction::Xor:
5062 return Constant::getNullValue(I->getType());
5063 case Instruction::Shl:
5064 case Instruction::Shr:
5065 return Constant::getNullValue(Type::UByteTy);
5066 case Instruction::And:
5067 return ConstantInt::getAllOnesValue(I->getType());
5068 case Instruction::Mul:
5069 return ConstantInt::get(I->getType(), 1);
5070 }
5071}
5072
Chris Lattner411336f2005-01-19 21:50:18 +00005073/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5074/// have the same opcode and only one use each. Try to simplify this.
5075Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5076 Instruction *FI) {
5077 if (TI->getNumOperands() == 1) {
5078 // If this is a non-volatile load or a cast from the same type,
5079 // merge.
5080 if (TI->getOpcode() == Instruction::Cast) {
5081 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5082 return 0;
5083 } else {
5084 return 0; // unknown unary op.
5085 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005086
Chris Lattner411336f2005-01-19 21:50:18 +00005087 // Fold this by inserting a select from the input values.
5088 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5089 FI->getOperand(0), SI.getName()+".v");
5090 InsertNewInstBefore(NewSI, SI);
5091 return new CastInst(NewSI, TI->getType());
5092 }
5093
5094 // Only handle binary operators here.
5095 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5096 return 0;
5097
5098 // Figure out if the operations have any operands in common.
5099 Value *MatchOp, *OtherOpT, *OtherOpF;
5100 bool MatchIsOpZero;
5101 if (TI->getOperand(0) == FI->getOperand(0)) {
5102 MatchOp = TI->getOperand(0);
5103 OtherOpT = TI->getOperand(1);
5104 OtherOpF = FI->getOperand(1);
5105 MatchIsOpZero = true;
5106 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5107 MatchOp = TI->getOperand(1);
5108 OtherOpT = TI->getOperand(0);
5109 OtherOpF = FI->getOperand(0);
5110 MatchIsOpZero = false;
5111 } else if (!TI->isCommutative()) {
5112 return 0;
5113 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5114 MatchOp = TI->getOperand(0);
5115 OtherOpT = TI->getOperand(1);
5116 OtherOpF = FI->getOperand(0);
5117 MatchIsOpZero = true;
5118 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5119 MatchOp = TI->getOperand(1);
5120 OtherOpT = TI->getOperand(0);
5121 OtherOpF = FI->getOperand(1);
5122 MatchIsOpZero = true;
5123 } else {
5124 return 0;
5125 }
5126
5127 // If we reach here, they do have operations in common.
5128 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5129 OtherOpF, SI.getName()+".v");
5130 InsertNewInstBefore(NewSI, SI);
5131
5132 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5133 if (MatchIsOpZero)
5134 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5135 else
5136 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5137 } else {
5138 if (MatchIsOpZero)
5139 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5140 else
5141 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5142 }
5143}
5144
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005145Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005146 Value *CondVal = SI.getCondition();
5147 Value *TrueVal = SI.getTrueValue();
5148 Value *FalseVal = SI.getFalseValue();
5149
5150 // select true, X, Y -> X
5151 // select false, X, Y -> Y
5152 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005153 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005154 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005155 else {
5156 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005157 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005158 }
Chris Lattner533bc492004-03-30 19:37:13 +00005159
5160 // select C, X, X -> X
5161 if (TrueVal == FalseVal)
5162 return ReplaceInstUsesWith(SI, TrueVal);
5163
Chris Lattner81a7a232004-10-16 18:11:37 +00005164 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5165 return ReplaceInstUsesWith(SI, FalseVal);
5166 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5167 return ReplaceInstUsesWith(SI, TrueVal);
5168 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5169 if (isa<Constant>(TrueVal))
5170 return ReplaceInstUsesWith(SI, TrueVal);
5171 else
5172 return ReplaceInstUsesWith(SI, FalseVal);
5173 }
5174
Chris Lattner1c631e82004-04-08 04:43:23 +00005175 if (SI.getType() == Type::BoolTy)
5176 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5177 if (C == ConstantBool::True) {
5178 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005179 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005180 } else {
5181 // Change: A = select B, false, C --> A = and !B, C
5182 Value *NotCond =
5183 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5184 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005185 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005186 }
5187 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5188 if (C == ConstantBool::False) {
5189 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005190 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005191 } else {
5192 // Change: A = select B, C, true --> A = or !B, C
5193 Value *NotCond =
5194 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5195 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005196 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005197 }
5198 }
5199
Chris Lattner183b3362004-04-09 19:05:30 +00005200 // Selecting between two integer constants?
5201 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5202 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5203 // select C, 1, 0 -> cast C to int
5204 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5205 return new CastInst(CondVal, SI.getType());
5206 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5207 // select C, 0, 1 -> cast !C to int
5208 Value *NotCond =
5209 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005210 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005211 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005212 }
Chris Lattner35167c32004-06-09 07:59:58 +00005213
5214 // If one of the constants is zero (we know they can't both be) and we
5215 // have a setcc instruction with zero, and we have an 'and' with the
5216 // non-constant value, eliminate this whole mess. This corresponds to
5217 // cases like this: ((X & 27) ? 27 : 0)
5218 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5219 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5220 if ((IC->getOpcode() == Instruction::SetEQ ||
5221 IC->getOpcode() == Instruction::SetNE) &&
5222 isa<ConstantInt>(IC->getOperand(1)) &&
5223 cast<Constant>(IC->getOperand(1))->isNullValue())
5224 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5225 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005226 isa<ConstantInt>(ICA->getOperand(1)) &&
5227 (ICA->getOperand(1) == TrueValC ||
5228 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005229 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5230 // Okay, now we know that everything is set up, we just don't
5231 // know whether we have a setne or seteq and whether the true or
5232 // false val is the zero.
5233 bool ShouldNotVal = !TrueValC->isNullValue();
5234 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5235 Value *V = ICA;
5236 if (ShouldNotVal)
5237 V = InsertNewInstBefore(BinaryOperator::create(
5238 Instruction::Xor, V, ICA->getOperand(1)), SI);
5239 return ReplaceInstUsesWith(SI, V);
5240 }
Chris Lattner533bc492004-03-30 19:37:13 +00005241 }
Chris Lattner623fba12004-04-10 22:21:27 +00005242
5243 // See if we are selecting two values based on a comparison of the two values.
5244 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5245 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5246 // Transform (X == Y) ? X : Y -> Y
5247 if (SCI->getOpcode() == Instruction::SetEQ)
5248 return ReplaceInstUsesWith(SI, FalseVal);
5249 // Transform (X != Y) ? X : Y -> X
5250 if (SCI->getOpcode() == Instruction::SetNE)
5251 return ReplaceInstUsesWith(SI, TrueVal);
5252 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5253
5254 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5255 // Transform (X == Y) ? Y : X -> X
5256 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005257 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005258 // Transform (X != Y) ? Y : X -> Y
5259 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005260 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005261 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5262 }
5263 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005264
Chris Lattnera04c9042005-01-13 22:52:24 +00005265 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5266 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5267 if (TI->hasOneUse() && FI->hasOneUse()) {
5268 bool isInverse = false;
5269 Instruction *AddOp = 0, *SubOp = 0;
5270
Chris Lattner411336f2005-01-19 21:50:18 +00005271 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5272 if (TI->getOpcode() == FI->getOpcode())
5273 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5274 return IV;
5275
5276 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5277 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005278 if (TI->getOpcode() == Instruction::Sub &&
5279 FI->getOpcode() == Instruction::Add) {
5280 AddOp = FI; SubOp = TI;
5281 } else if (FI->getOpcode() == Instruction::Sub &&
5282 TI->getOpcode() == Instruction::Add) {
5283 AddOp = TI; SubOp = FI;
5284 }
5285
5286 if (AddOp) {
5287 Value *OtherAddOp = 0;
5288 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5289 OtherAddOp = AddOp->getOperand(1);
5290 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5291 OtherAddOp = AddOp->getOperand(0);
5292 }
5293
5294 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005295 // So at this point we know we have (Y -> OtherAddOp):
5296 // select C, (add X, Y), (sub X, Z)
5297 Value *NegVal; // Compute -Z
5298 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5299 NegVal = ConstantExpr::getNeg(C);
5300 } else {
5301 NegVal = InsertNewInstBefore(
5302 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005303 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005304
5305 Value *NewTrueOp = OtherAddOp;
5306 Value *NewFalseOp = NegVal;
5307 if (AddOp != TI)
5308 std::swap(NewTrueOp, NewFalseOp);
5309 Instruction *NewSel =
5310 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5311
5312 NewSel = InsertNewInstBefore(NewSel, SI);
5313 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005314 }
5315 }
5316 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005317
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005318 // See if we can fold the select into one of our operands.
5319 if (SI.getType()->isInteger()) {
5320 // See the comment above GetSelectFoldableOperands for a description of the
5321 // transformation we are doing here.
5322 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5323 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5324 !isa<Constant>(FalseVal))
5325 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5326 unsigned OpToFold = 0;
5327 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5328 OpToFold = 1;
5329 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5330 OpToFold = 2;
5331 }
5332
5333 if (OpToFold) {
5334 Constant *C = GetSelectFoldableConstant(TVI);
5335 std::string Name = TVI->getName(); TVI->setName("");
5336 Instruction *NewSel =
5337 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5338 Name);
5339 InsertNewInstBefore(NewSel, SI);
5340 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5341 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5342 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5343 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5344 else {
5345 assert(0 && "Unknown instruction!!");
5346 }
5347 }
5348 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005349
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005350 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5351 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5352 !isa<Constant>(TrueVal))
5353 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5354 unsigned OpToFold = 0;
5355 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5356 OpToFold = 1;
5357 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5358 OpToFold = 2;
5359 }
5360
5361 if (OpToFold) {
5362 Constant *C = GetSelectFoldableConstant(FVI);
5363 std::string Name = FVI->getName(); FVI->setName("");
5364 Instruction *NewSel =
5365 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5366 Name);
5367 InsertNewInstBefore(NewSel, SI);
5368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5369 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5370 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5371 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5372 else {
5373 assert(0 && "Unknown instruction!!");
5374 }
5375 }
5376 }
5377 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005378
5379 if (BinaryOperator::isNot(CondVal)) {
5380 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5381 SI.setOperand(1, FalseVal);
5382 SI.setOperand(2, TrueVal);
5383 return &SI;
5384 }
5385
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005386 return 0;
5387}
5388
Chris Lattner82f2ef22006-03-06 20:18:44 +00005389/// GetKnownAlignment - If the specified pointer has an alignment that we can
5390/// determine, return it, otherwise return 0.
5391static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5392 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5393 unsigned Align = GV->getAlignment();
5394 if (Align == 0 && TD)
5395 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5396 return Align;
5397 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5398 unsigned Align = AI->getAlignment();
5399 if (Align == 0 && TD) {
5400 if (isa<AllocaInst>(AI))
5401 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5402 else if (isa<MallocInst>(AI)) {
5403 // Malloc returns maximally aligned memory.
5404 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5405 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5406 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5407 }
5408 }
5409 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005410 } else if (isa<CastInst>(V) ||
5411 (isa<ConstantExpr>(V) &&
5412 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5413 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005414 if (isa<PointerType>(CI->getOperand(0)->getType()))
5415 return GetKnownAlignment(CI->getOperand(0), TD);
5416 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005417 } else if (isa<GetElementPtrInst>(V) ||
5418 (isa<ConstantExpr>(V) &&
5419 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5420 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005421 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5422 if (BaseAlignment == 0) return 0;
5423
5424 // If all indexes are zero, it is just the alignment of the base pointer.
5425 bool AllZeroOperands = true;
5426 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5427 if (!isa<Constant>(GEPI->getOperand(i)) ||
5428 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5429 AllZeroOperands = false;
5430 break;
5431 }
5432 if (AllZeroOperands)
5433 return BaseAlignment;
5434
5435 // Otherwise, if the base alignment is >= the alignment we expect for the
5436 // base pointer type, then we know that the resultant pointer is aligned at
5437 // least as much as its type requires.
5438 if (!TD) return 0;
5439
5440 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5441 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005442 <= BaseAlignment) {
5443 const Type *GEPTy = GEPI->getType();
5444 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5445 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005446 return 0;
5447 }
5448 return 0;
5449}
5450
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005451
Chris Lattnerc66b2232006-01-13 20:11:04 +00005452/// visitCallInst - CallInst simplification. This mostly only handles folding
5453/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5454/// the heavy lifting.
5455///
Chris Lattner970c33a2003-06-19 17:00:31 +00005456Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005457 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5458 if (!II) return visitCallSite(&CI);
5459
Chris Lattner51ea1272004-02-28 05:22:00 +00005460 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5461 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005462 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005463 bool Changed = false;
5464
5465 // memmove/cpy/set of zero bytes is a noop.
5466 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5467 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5468
Chris Lattner00648e12004-10-12 04:52:52 +00005469 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5470 if (CI->getRawValue() == 1) {
5471 // Replace the instruction with just byte operations. We would
5472 // transform other cases to loads/stores, but we don't know if
5473 // alignment is sufficient.
5474 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005475 }
5476
Chris Lattner00648e12004-10-12 04:52:52 +00005477 // If we have a memmove and the source operation is a constant global,
5478 // then the source and dest pointers can't alias, so we can change this
5479 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005480 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005481 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5482 if (GVSrc->isConstant()) {
5483 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005484 const char *Name;
5485 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5486 Type::UIntTy)
5487 Name = "llvm.memcpy.i32";
5488 else
5489 Name = "llvm.memcpy.i64";
5490 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00005491 CI.getCalledFunction()->getFunctionType());
5492 CI.setOperand(0, MemCpy);
5493 Changed = true;
5494 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005495 }
Chris Lattner00648e12004-10-12 04:52:52 +00005496
Chris Lattner82f2ef22006-03-06 20:18:44 +00005497 // If we can determine a pointer alignment that is bigger than currently
5498 // set, update the alignment.
5499 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5500 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5501 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5502 unsigned Align = std::min(Alignment1, Alignment2);
5503 if (MI->getAlignment()->getRawValue() < Align) {
5504 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5505 Changed = true;
5506 }
5507 } else if (isa<MemSetInst>(MI)) {
5508 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5509 if (MI->getAlignment()->getRawValue() < Alignment) {
5510 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5511 Changed = true;
5512 }
5513 }
5514
Chris Lattnerc66b2232006-01-13 20:11:04 +00005515 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00005516 } else {
5517 switch (II->getIntrinsicID()) {
5518 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005519 case Intrinsic::ppc_altivec_lvx:
5520 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00005521 case Intrinsic::x86_sse_loadu_ps:
5522 case Intrinsic::x86_sse2_loadu_pd:
5523 case Intrinsic::x86_sse2_loadu_dq:
5524 // Turn PPC lvx -> load if the pointer is known aligned.
5525 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005526 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005527 Value *Ptr = InsertCastBefore(II->getOperand(1),
5528 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005529 return new LoadInst(Ptr);
5530 }
5531 break;
5532 case Intrinsic::ppc_altivec_stvx:
5533 case Intrinsic::ppc_altivec_stvxl:
5534 // Turn stvx -> store if the pointer is known aligned.
5535 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005536 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5537 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005538 return new StoreInst(II->getOperand(1), Ptr);
5539 }
5540 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00005541 case Intrinsic::x86_sse_storeu_ps:
5542 case Intrinsic::x86_sse2_storeu_pd:
5543 case Intrinsic::x86_sse2_storeu_dq:
5544 case Intrinsic::x86_sse2_storel_dq:
5545 // Turn X86 storeu -> store if the pointer is known aligned.
5546 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5547 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5548 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5549 return new StoreInst(II->getOperand(2), Ptr);
5550 }
5551 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00005552 case Intrinsic::ppc_altivec_vperm:
5553 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5554 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5555 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5556
5557 // Check that all of the elements are integer constants or undefs.
5558 bool AllEltsOk = true;
5559 for (unsigned i = 0; i != 16; ++i) {
5560 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5561 !isa<UndefValue>(Mask->getOperand(i))) {
5562 AllEltsOk = false;
5563 break;
5564 }
5565 }
5566
5567 if (AllEltsOk) {
5568 // Cast the input vectors to byte vectors.
5569 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5570 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5571 Value *Result = UndefValue::get(Op0->getType());
5572
5573 // Only extract each element once.
5574 Value *ExtractedElts[32];
5575 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5576
5577 for (unsigned i = 0; i != 16; ++i) {
5578 if (isa<UndefValue>(Mask->getOperand(i)))
5579 continue;
5580 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5581 Idx &= 31; // Match the hardware behavior.
5582
5583 if (ExtractedElts[Idx] == 0) {
5584 Instruction *Elt =
5585 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5586 ConstantUInt::get(Type::UIntTy, Idx&15),
5587 "tmp");
5588 InsertNewInstBefore(Elt, CI);
5589 ExtractedElts[Idx] = Elt;
5590 }
5591
5592 // Insert this value into the result vector.
5593 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5594 ConstantUInt::get(Type::UIntTy, i),
5595 "tmp");
5596 InsertNewInstBefore(cast<Instruction>(Result), CI);
5597 }
5598 return new CastInst(Result, CI.getType());
5599 }
5600 }
5601 break;
5602
Chris Lattner503221f2006-01-13 21:28:09 +00005603 case Intrinsic::stackrestore: {
5604 // If the save is right next to the restore, remove the restore. This can
5605 // happen when variable allocas are DCE'd.
5606 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5607 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5608 BasicBlock::iterator BI = SS;
5609 if (&*++BI == II)
5610 return EraseInstFromFunction(CI);
5611 }
5612 }
5613
5614 // If the stack restore is in a return/unwind block and if there are no
5615 // allocas or calls between the restore and the return, nuke the restore.
5616 TerminatorInst *TI = II->getParent()->getTerminator();
5617 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5618 BasicBlock::iterator BI = II;
5619 bool CannotRemove = false;
5620 for (++BI; &*BI != TI; ++BI) {
5621 if (isa<AllocaInst>(BI) ||
5622 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5623 CannotRemove = true;
5624 break;
5625 }
5626 }
5627 if (!CannotRemove)
5628 return EraseInstFromFunction(CI);
5629 }
5630 break;
5631 }
5632 }
Chris Lattner00648e12004-10-12 04:52:52 +00005633 }
5634
Chris Lattnerc66b2232006-01-13 20:11:04 +00005635 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005636}
5637
5638// InvokeInst simplification
5639//
5640Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005641 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005642}
5643
Chris Lattneraec3d942003-10-07 22:32:43 +00005644// visitCallSite - Improvements for call and invoke instructions.
5645//
5646Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005647 bool Changed = false;
5648
5649 // If the callee is a constexpr cast of a function, attempt to move the cast
5650 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005651 if (transformConstExprCastCall(CS)) return 0;
5652
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005653 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005654
Chris Lattner61d9d812005-05-13 07:09:09 +00005655 if (Function *CalleeF = dyn_cast<Function>(Callee))
5656 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5657 Instruction *OldCall = CS.getInstruction();
5658 // If the call and callee calling conventions don't match, this call must
5659 // be unreachable, as the call is undefined.
5660 new StoreInst(ConstantBool::True,
5661 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5662 if (!OldCall->use_empty())
5663 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5664 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5665 return EraseInstFromFunction(*OldCall);
5666 return 0;
5667 }
5668
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005669 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5670 // This instruction is not reachable, just remove it. We insert a store to
5671 // undef so that we know that this code is not reachable, despite the fact
5672 // that we can't modify the CFG here.
5673 new StoreInst(ConstantBool::True,
5674 UndefValue::get(PointerType::get(Type::BoolTy)),
5675 CS.getInstruction());
5676
5677 if (!CS.getInstruction()->use_empty())
5678 CS.getInstruction()->
5679 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5680
5681 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5682 // Don't break the CFG, insert a dummy cond branch.
5683 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5684 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005685 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005686 return EraseInstFromFunction(*CS.getInstruction());
5687 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005688
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005689 const PointerType *PTy = cast<PointerType>(Callee->getType());
5690 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5691 if (FTy->isVarArg()) {
5692 // See if we can optimize any arguments passed through the varargs area of
5693 // the call.
5694 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5695 E = CS.arg_end(); I != E; ++I)
5696 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5697 // If this cast does not effect the value passed through the varargs
5698 // area, we can eliminate the use of the cast.
5699 Value *Op = CI->getOperand(0);
5700 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5701 *I = Op;
5702 Changed = true;
5703 }
5704 }
5705 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005706
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005707 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005708}
5709
Chris Lattner970c33a2003-06-19 17:00:31 +00005710// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5711// attempt to move the cast to the arguments of the call/invoke.
5712//
5713bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5714 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5715 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005716 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005717 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005718 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005719 Instruction *Caller = CS.getInstruction();
5720
5721 // Okay, this is a cast from a function to a different type. Unless doing so
5722 // would cause a type conversion of one of our arguments, change this call to
5723 // be a direct call with arguments casted to the appropriate types.
5724 //
5725 const FunctionType *FT = Callee->getFunctionType();
5726 const Type *OldRetTy = Caller->getType();
5727
Chris Lattner1f7942f2004-01-14 06:06:08 +00005728 // Check to see if we are changing the return type...
5729 if (OldRetTy != FT->getReturnType()) {
5730 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00005731 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5732 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00005733 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00005734 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005735 return false; // Cannot transform this return value...
5736
5737 // If the callsite is an invoke instruction, and the return value is used by
5738 // a PHI node in a successor, we cannot change the return type of the call
5739 // because there is no place to put the cast instruction (without breaking
5740 // the critical edge). Bail out in this case.
5741 if (!Caller->use_empty())
5742 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5743 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5744 UI != E; ++UI)
5745 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5746 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005747 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005748 return false;
5749 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005750
5751 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5752 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005753
Chris Lattner970c33a2003-06-19 17:00:31 +00005754 CallSite::arg_iterator AI = CS.arg_begin();
5755 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5756 const Type *ParamTy = FT->getParamType(i);
5757 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005758 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005759 }
5760
5761 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5762 Callee->isExternal())
5763 return false; // Do not delete arguments unless we have a function body...
5764
5765 // Okay, we decided that this is a safe thing to do: go ahead and start
5766 // inserting cast instructions as necessary...
5767 std::vector<Value*> Args;
5768 Args.reserve(NumActualArgs);
5769
5770 AI = CS.arg_begin();
5771 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5772 const Type *ParamTy = FT->getParamType(i);
5773 if ((*AI)->getType() == ParamTy) {
5774 Args.push_back(*AI);
5775 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005776 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5777 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005778 }
5779 }
5780
5781 // If the function takes more arguments than the call was taking, add them
5782 // now...
5783 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5784 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5785
5786 // If we are removing arguments to the function, emit an obnoxious warning...
5787 if (FT->getNumParams() < NumActualArgs)
5788 if (!FT->isVarArg()) {
5789 std::cerr << "WARNING: While resolving call to function '"
5790 << Callee->getName() << "' arguments were dropped!\n";
5791 } else {
5792 // Add all of the arguments in their promoted form to the arg list...
5793 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5794 const Type *PTy = getPromotedType((*AI)->getType());
5795 if (PTy != (*AI)->getType()) {
5796 // Must promote to pass through va_arg area!
5797 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5798 InsertNewInstBefore(Cast, *Caller);
5799 Args.push_back(Cast);
5800 } else {
5801 Args.push_back(*AI);
5802 }
5803 }
5804 }
5805
5806 if (FT->getReturnType() == Type::VoidTy)
5807 Caller->setName(""); // Void type should not have a name...
5808
5809 Instruction *NC;
5810 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005811 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005812 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005813 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005814 } else {
5815 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005816 if (cast<CallInst>(Caller)->isTailCall())
5817 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005818 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005819 }
5820
5821 // Insert a cast of the return type as necessary...
5822 Value *NV = NC;
5823 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5824 if (NV->getType() != Type::VoidTy) {
5825 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005826
5827 // If this is an invoke instruction, we should insert it after the first
5828 // non-phi, instruction in the normal successor block.
5829 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5830 BasicBlock::iterator I = II->getNormalDest()->begin();
5831 while (isa<PHINode>(I)) ++I;
5832 InsertNewInstBefore(NC, *I);
5833 } else {
5834 // Otherwise, it's a call, just insert cast right after the call instr
5835 InsertNewInstBefore(NC, *Caller);
5836 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005837 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005838 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005839 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005840 }
5841 }
5842
5843 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5844 Caller->replaceAllUsesWith(NV);
5845 Caller->getParent()->getInstList().erase(Caller);
5846 removeFromWorkList(Caller);
5847 return true;
5848}
5849
5850
Chris Lattner7515cab2004-11-14 19:13:23 +00005851// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5852// operator and they all are only used by the PHI, PHI together their
5853// inputs, and do the operation once, to the result of the PHI.
5854Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5855 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5856
5857 // Scan the instruction, looking for input operations that can be folded away.
5858 // If all input operands to the phi are the same instruction (e.g. a cast from
5859 // the same type or "+42") we can pull the operation through the PHI, reducing
5860 // code size and simplifying code.
5861 Constant *ConstantOp = 0;
5862 const Type *CastSrcTy = 0;
5863 if (isa<CastInst>(FirstInst)) {
5864 CastSrcTy = FirstInst->getOperand(0)->getType();
5865 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5866 // Can fold binop or shift if the RHS is a constant.
5867 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5868 if (ConstantOp == 0) return 0;
5869 } else {
5870 return 0; // Cannot fold this operation.
5871 }
5872
5873 // Check to see if all arguments are the same operation.
5874 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5875 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5876 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5877 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5878 return 0;
5879 if (CastSrcTy) {
5880 if (I->getOperand(0)->getType() != CastSrcTy)
5881 return 0; // Cast operation must match.
5882 } else if (I->getOperand(1) != ConstantOp) {
5883 return 0;
5884 }
5885 }
5886
5887 // Okay, they are all the same operation. Create a new PHI node of the
5888 // correct type, and PHI together all of the LHS's of the instructions.
5889 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5890 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005891 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005892
5893 Value *InVal = FirstInst->getOperand(0);
5894 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005895
5896 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005897 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5898 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5899 if (NewInVal != InVal)
5900 InVal = 0;
5901 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5902 }
5903
5904 Value *PhiVal;
5905 if (InVal) {
5906 // The new PHI unions all of the same values together. This is really
5907 // common, so we handle it intelligently here for compile-time speed.
5908 PhiVal = InVal;
5909 delete NewPN;
5910 } else {
5911 InsertNewInstBefore(NewPN, PN);
5912 PhiVal = NewPN;
5913 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005914
Chris Lattner7515cab2004-11-14 19:13:23 +00005915 // Insert and return the new operation.
5916 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005917 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005918 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005919 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005920 else
5921 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005922 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005923}
Chris Lattner48a44f72002-05-02 17:06:02 +00005924
Chris Lattner71536432005-01-17 05:10:15 +00005925/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5926/// that is dead.
5927static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5928 if (PN->use_empty()) return true;
5929 if (!PN->hasOneUse()) return false;
5930
5931 // Remember this node, and if we find the cycle, return.
5932 if (!PotentiallyDeadPHIs.insert(PN).second)
5933 return true;
5934
5935 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5936 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005937
Chris Lattner71536432005-01-17 05:10:15 +00005938 return false;
5939}
5940
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005941// PHINode simplification
5942//
Chris Lattner113f4f42002-06-25 16:13:24 +00005943Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005944 if (Value *V = PN.hasConstantValue())
5945 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005946
5947 // If the only user of this instruction is a cast instruction, and all of the
5948 // incoming values are constants, change this PHI to merge together the casted
5949 // constants.
5950 if (PN.hasOneUse())
5951 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5952 if (CI->getType() != PN.getType()) { // noop casts will be folded
5953 bool AllConstant = true;
5954 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5955 if (!isa<Constant>(PN.getIncomingValue(i))) {
5956 AllConstant = false;
5957 break;
5958 }
5959 if (AllConstant) {
5960 // Make a new PHI with all casted values.
5961 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5962 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5963 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5964 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5965 PN.getIncomingBlock(i));
5966 }
5967
5968 // Update the cast instruction.
5969 CI->setOperand(0, New);
5970 WorkList.push_back(CI); // revisit the cast instruction to fold.
5971 WorkList.push_back(New); // Make sure to revisit the new Phi
5972 return &PN; // PN is now dead!
5973 }
5974 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005975
5976 // If all PHI operands are the same operation, pull them through the PHI,
5977 // reducing code size.
5978 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5979 PN.getIncomingValue(0)->hasOneUse())
5980 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5981 return Result;
5982
Chris Lattner71536432005-01-17 05:10:15 +00005983 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5984 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5985 // PHI)... break the cycle.
5986 if (PN.hasOneUse())
5987 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5988 std::set<PHINode*> PotentiallyDeadPHIs;
5989 PotentiallyDeadPHIs.insert(&PN);
5990 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5991 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5992 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005993
Chris Lattner91daeb52003-12-19 05:58:40 +00005994 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005995}
5996
Chris Lattner69193f92004-04-05 01:30:19 +00005997static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5998 Instruction *InsertPoint,
5999 InstCombiner *IC) {
6000 unsigned PS = IC->getTargetData().getPointerSize();
6001 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006002 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6003 // We must insert a cast to ensure we sign-extend.
6004 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6005 V->getName()), *InsertPoint);
6006 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6007 *InsertPoint);
6008}
6009
Chris Lattner48a44f72002-05-02 17:06:02 +00006010
Chris Lattner113f4f42002-06-25 16:13:24 +00006011Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006012 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006013 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006014 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006015 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006016 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006017
Chris Lattner81a7a232004-10-16 18:11:37 +00006018 if (isa<UndefValue>(GEP.getOperand(0)))
6019 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6020
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006021 bool HasZeroPointerIndex = false;
6022 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6023 HasZeroPointerIndex = C->isNullValue();
6024
6025 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006026 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006027
Chris Lattner69193f92004-04-05 01:30:19 +00006028 // Eliminate unneeded casts for indices.
6029 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006030 gep_type_iterator GTI = gep_type_begin(GEP);
6031 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6032 if (isa<SequentialType>(*GTI)) {
6033 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6034 Value *Src = CI->getOperand(0);
6035 const Type *SrcTy = Src->getType();
6036 const Type *DestTy = CI->getType();
6037 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006038 if (SrcTy->getPrimitiveSizeInBits() ==
6039 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006040 // We can always eliminate a cast from ulong or long to the other.
6041 // We can always eliminate a cast from uint to int or the other on
6042 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006043 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006044 MadeChange = true;
6045 GEP.setOperand(i, Src);
6046 }
6047 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6048 SrcTy->getPrimitiveSize() == 4) {
6049 // We can always eliminate a cast from int to [u]long. We can
6050 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6051 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006052 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006053 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006054 MadeChange = true;
6055 GEP.setOperand(i, Src);
6056 }
Chris Lattner69193f92004-04-05 01:30:19 +00006057 }
6058 }
6059 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006060 // If we are using a wider index than needed for this platform, shrink it
6061 // to what we need. If the incoming value needs a cast instruction,
6062 // insert it. This explicit cast can make subsequent optimizations more
6063 // obvious.
6064 Value *Op = GEP.getOperand(i);
6065 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006066 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006067 GEP.setOperand(i, ConstantExpr::getCast(C,
6068 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006069 MadeChange = true;
6070 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006071 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6072 Op->getName()), GEP);
6073 GEP.setOperand(i, Op);
6074 MadeChange = true;
6075 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006076
6077 // If this is a constant idx, make sure to canonicalize it to be a signed
6078 // operand, otherwise CSE and other optimizations are pessimized.
6079 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6080 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6081 CUI->getType()->getSignedVersion()));
6082 MadeChange = true;
6083 }
Chris Lattner69193f92004-04-05 01:30:19 +00006084 }
6085 if (MadeChange) return &GEP;
6086
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006087 // Combine Indices - If the source pointer to this getelementptr instruction
6088 // is a getelementptr instruction, combine the indices of the two
6089 // getelementptr instructions into a single instruction.
6090 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006091 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006092 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006093 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006094
6095 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006096 // Note that if our source is a gep chain itself that we wait for that
6097 // chain to be resolved before we perform this transformation. This
6098 // avoids us creating a TON of code in some cases.
6099 //
6100 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6101 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6102 return 0; // Wait until our source is folded to completion.
6103
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006104 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006105
6106 // Find out whether the last index in the source GEP is a sequential idx.
6107 bool EndsWithSequential = false;
6108 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6109 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006110 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006111
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006112 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006113 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006114 // Replace: gep (gep %P, long B), long A, ...
6115 // With: T = long A+B; gep %P, T, ...
6116 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006117 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006118 if (SO1 == Constant::getNullValue(SO1->getType())) {
6119 Sum = GO1;
6120 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6121 Sum = SO1;
6122 } else {
6123 // If they aren't the same type, convert both to an integer of the
6124 // target's pointer size.
6125 if (SO1->getType() != GO1->getType()) {
6126 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6127 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6128 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6129 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6130 } else {
6131 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006132 if (SO1->getType()->getPrimitiveSize() == PS) {
6133 // Convert GO1 to SO1's type.
6134 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6135
6136 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6137 // Convert SO1 to GO1's type.
6138 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6139 } else {
6140 const Type *PT = TD->getIntPtrType();
6141 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6142 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6143 }
6144 }
6145 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006146 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6147 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6148 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006149 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6150 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006151 }
Chris Lattner69193f92004-04-05 01:30:19 +00006152 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006153
6154 // Recycle the GEP we already have if possible.
6155 if (SrcGEPOperands.size() == 2) {
6156 GEP.setOperand(0, SrcGEPOperands[0]);
6157 GEP.setOperand(1, Sum);
6158 return &GEP;
6159 } else {
6160 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6161 SrcGEPOperands.end()-1);
6162 Indices.push_back(Sum);
6163 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6164 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006165 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006166 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006167 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006168 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006169 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6170 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006171 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6172 }
6173
6174 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006175 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006176
Chris Lattner5f667a62004-05-07 22:09:22 +00006177 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006178 // GEP of global variable. If all of the indices for this GEP are
6179 // constants, we can promote this to a constexpr instead of an instruction.
6180
6181 // Scan for nonconstants...
6182 std::vector<Constant*> Indices;
6183 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6184 for (; I != E && isa<Constant>(*I); ++I)
6185 Indices.push_back(cast<Constant>(*I));
6186
6187 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006188 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006189
6190 // Replace all uses of the GEP with the new constexpr...
6191 return ReplaceInstUsesWith(GEP, CE);
6192 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006193 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6194 if (!isa<PointerType>(X->getType())) {
6195 // Not interesting. Source pointer must be a cast from pointer.
6196 } else if (HasZeroPointerIndex) {
6197 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6198 // into : GEP [10 x ubyte]* X, long 0, ...
6199 //
6200 // This occurs when the program declares an array extern like "int X[];"
6201 //
6202 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6203 const PointerType *XTy = cast<PointerType>(X->getType());
6204 if (const ArrayType *XATy =
6205 dyn_cast<ArrayType>(XTy->getElementType()))
6206 if (const ArrayType *CATy =
6207 dyn_cast<ArrayType>(CPTy->getElementType()))
6208 if (CATy->getElementType() == XATy->getElementType()) {
6209 // At this point, we know that the cast source type is a pointer
6210 // to an array of the same type as the destination pointer
6211 // array. Because the array type is never stepped over (there
6212 // is a leading zero) we can fold the cast into this GEP.
6213 GEP.setOperand(0, X);
6214 return &GEP;
6215 }
6216 } else if (GEP.getNumOperands() == 2) {
6217 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006218 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6219 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006220 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6221 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6222 if (isa<ArrayType>(SrcElTy) &&
6223 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6224 TD->getTypeSize(ResElTy)) {
6225 Value *V = InsertNewInstBefore(
6226 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6227 GEP.getOperand(1), GEP.getName()), GEP);
6228 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006229 }
Chris Lattner2a893292005-09-13 18:36:04 +00006230
6231 // Transform things like:
6232 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6233 // (where tmp = 8*tmp2) into:
6234 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6235
6236 if (isa<ArrayType>(SrcElTy) &&
6237 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6238 uint64_t ArrayEltSize =
6239 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6240
6241 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6242 // allow either a mul, shift, or constant here.
6243 Value *NewIdx = 0;
6244 ConstantInt *Scale = 0;
6245 if (ArrayEltSize == 1) {
6246 NewIdx = GEP.getOperand(1);
6247 Scale = ConstantInt::get(NewIdx->getType(), 1);
6248 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006249 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006250 Scale = CI;
6251 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6252 if (Inst->getOpcode() == Instruction::Shl &&
6253 isa<ConstantInt>(Inst->getOperand(1))) {
6254 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6255 if (Inst->getType()->isSigned())
6256 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6257 else
6258 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6259 NewIdx = Inst->getOperand(0);
6260 } else if (Inst->getOpcode() == Instruction::Mul &&
6261 isa<ConstantInt>(Inst->getOperand(1))) {
6262 Scale = cast<ConstantInt>(Inst->getOperand(1));
6263 NewIdx = Inst->getOperand(0);
6264 }
6265 }
6266
6267 // If the index will be to exactly the right offset with the scale taken
6268 // out, perform the transformation.
6269 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6270 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6271 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006272 (int64_t)C->getRawValue() /
6273 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006274 else
6275 Scale = ConstantUInt::get(Scale->getType(),
6276 Scale->getRawValue() / ArrayEltSize);
6277 if (Scale->getRawValue() != 1) {
6278 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6279 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6280 NewIdx = InsertNewInstBefore(Sc, GEP);
6281 }
6282
6283 // Insert the new GEP instruction.
6284 Instruction *Idx =
6285 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6286 NewIdx, GEP.getName());
6287 Idx = InsertNewInstBefore(Idx, GEP);
6288 return new CastInst(Idx, GEP.getType());
6289 }
6290 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006291 }
Chris Lattnerca081252001-12-14 16:52:21 +00006292 }
6293
Chris Lattnerca081252001-12-14 16:52:21 +00006294 return 0;
6295}
6296
Chris Lattner1085bdf2002-11-04 16:18:53 +00006297Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6298 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6299 if (AI.isArrayAllocation()) // Check C != 1
6300 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6301 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006302 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006303
6304 // Create and insert the replacement instruction...
6305 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006306 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006307 else {
6308 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006309 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006310 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006311
6312 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006313
Chris Lattner1085bdf2002-11-04 16:18:53 +00006314 // Scan to the end of the allocation instructions, to skip over a block of
6315 // allocas if possible...
6316 //
6317 BasicBlock::iterator It = New;
6318 while (isa<AllocationInst>(*It)) ++It;
6319
6320 // Now that I is pointing to the first non-allocation-inst in the block,
6321 // insert our getelementptr instruction...
6322 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006323 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6324 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6325 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006326
6327 // Now make everything use the getelementptr instead of the original
6328 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006329 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006330 } else if (isa<UndefValue>(AI.getArraySize())) {
6331 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006332 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006333
6334 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6335 // Note that we only do this for alloca's, because malloc should allocate and
6336 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006337 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006338 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006339 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6340
Chris Lattner1085bdf2002-11-04 16:18:53 +00006341 return 0;
6342}
6343
Chris Lattner8427bff2003-12-07 01:24:23 +00006344Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6345 Value *Op = FI.getOperand(0);
6346
6347 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6348 if (CastInst *CI = dyn_cast<CastInst>(Op))
6349 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6350 FI.setOperand(0, CI->getOperand(0));
6351 return &FI;
6352 }
6353
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006354 // free undef -> unreachable.
6355 if (isa<UndefValue>(Op)) {
6356 // Insert a new store to null because we cannot modify the CFG here.
6357 new StoreInst(ConstantBool::True,
6358 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6359 return EraseInstFromFunction(FI);
6360 }
6361
Chris Lattnerf3a36602004-02-28 04:57:37 +00006362 // If we have 'free null' delete the instruction. This can happen in stl code
6363 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006364 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006365 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006366
Chris Lattner8427bff2003-12-07 01:24:23 +00006367 return 0;
6368}
6369
6370
Chris Lattner72684fe2005-01-31 05:51:45 +00006371/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006372static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6373 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006374 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006375
6376 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006377 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006378 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006379
Chris Lattnerebca4762006-04-02 05:37:12 +00006380 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6381 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006382 // If the source is an array, the code below will not succeed. Check to
6383 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6384 // constants.
6385 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6386 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6387 if (ASrcTy->getNumElements() != 0) {
6388 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6389 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6390 SrcTy = cast<PointerType>(CastOp->getType());
6391 SrcPTy = SrcTy->getElementType();
6392 }
6393
Chris Lattnerebca4762006-04-02 05:37:12 +00006394 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6395 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006396 // Do not allow turning this into a load of an integer, which is then
6397 // casted to a pointer, this pessimizes pointer analysis a lot.
6398 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006399 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006400 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006401
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006402 // Okay, we are casting from one integer or pointer type to another of
6403 // the same size. Instead of casting the pointer before the load, cast
6404 // the result of the loaded value.
6405 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6406 CI->getName(),
6407 LI.isVolatile()),LI);
6408 // Now cast the result of the load.
6409 return new CastInst(NewLoad, LI.getType());
6410 }
Chris Lattner35e24772004-07-13 01:49:43 +00006411 }
6412 }
6413 return 0;
6414}
6415
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006416/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006417/// from this value cannot trap. If it is not obviously safe to load from the
6418/// specified pointer, we do a quick local scan of the basic block containing
6419/// ScanFrom, to determine if the address is already accessed.
6420static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6421 // If it is an alloca or global variable, it is always safe to load from.
6422 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6423
6424 // Otherwise, be a little bit agressive by scanning the local block where we
6425 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006426 // from/to. If so, the previous load or store would have already trapped,
6427 // so there is no harm doing an extra load (also, CSE will later eliminate
6428 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006429 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6430
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006431 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006432 --BBI;
6433
6434 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6435 if (LI->getOperand(0) == V) return true;
6436 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6437 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006438
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006439 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006440 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006441}
6442
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006443Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6444 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006445
Chris Lattnera9d84e32005-05-01 04:24:53 +00006446 // load (cast X) --> cast (load X) iff safe
6447 if (CastInst *CI = dyn_cast<CastInst>(Op))
6448 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6449 return Res;
6450
6451 // None of the following transforms are legal for volatile loads.
6452 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006453
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006454 if (&LI.getParent()->front() != &LI) {
6455 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006456 // If the instruction immediately before this is a store to the same
6457 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006458 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6459 if (SI->getOperand(1) == LI.getOperand(0))
6460 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006461 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6462 if (LIB->getOperand(0) == LI.getOperand(0))
6463 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006464 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006465
6466 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6467 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6468 isa<UndefValue>(GEPI->getOperand(0))) {
6469 // Insert a new store to null instruction before the load to indicate
6470 // that this code is not reachable. We do this instead of inserting
6471 // an unreachable instruction directly because we cannot modify the
6472 // CFG.
6473 new StoreInst(UndefValue::get(LI.getType()),
6474 Constant::getNullValue(Op->getType()), &LI);
6475 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6476 }
6477
Chris Lattner81a7a232004-10-16 18:11:37 +00006478 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006479 // load null/undef -> undef
6480 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006481 // Insert a new store to null instruction before the load to indicate that
6482 // this code is not reachable. We do this instead of inserting an
6483 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006484 new StoreInst(UndefValue::get(LI.getType()),
6485 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006486 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006487 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006488
Chris Lattner81a7a232004-10-16 18:11:37 +00006489 // Instcombine load (constant global) into the value loaded.
6490 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6491 if (GV->isConstant() && !GV->isExternal())
6492 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006493
Chris Lattner81a7a232004-10-16 18:11:37 +00006494 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6495 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6496 if (CE->getOpcode() == Instruction::GetElementPtr) {
6497 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6498 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006499 if (Constant *V =
6500 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006501 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006502 if (CE->getOperand(0)->isNullValue()) {
6503 // Insert a new store to null instruction before the load to indicate
6504 // that this code is not reachable. We do this instead of inserting
6505 // an unreachable instruction directly because we cannot modify the
6506 // CFG.
6507 new StoreInst(UndefValue::get(LI.getType()),
6508 Constant::getNullValue(Op->getType()), &LI);
6509 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6510 }
6511
Chris Lattner81a7a232004-10-16 18:11:37 +00006512 } else if (CE->getOpcode() == Instruction::Cast) {
6513 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6514 return Res;
6515 }
6516 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006517
Chris Lattnera9d84e32005-05-01 04:24:53 +00006518 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006519 // Change select and PHI nodes to select values instead of addresses: this
6520 // helps alias analysis out a lot, allows many others simplifications, and
6521 // exposes redundancy in the code.
6522 //
6523 // Note that we cannot do the transformation unless we know that the
6524 // introduced loads cannot trap! Something like this is valid as long as
6525 // the condition is always false: load (select bool %C, int* null, int* %G),
6526 // but it would not be valid if we transformed it to load from null
6527 // unconditionally.
6528 //
6529 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6530 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006531 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6532 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006533 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006534 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006535 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006536 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006537 return new SelectInst(SI->getCondition(), V1, V2);
6538 }
6539
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006540 // load (select (cond, null, P)) -> load P
6541 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6542 if (C->isNullValue()) {
6543 LI.setOperand(0, SI->getOperand(2));
6544 return &LI;
6545 }
6546
6547 // load (select (cond, P, null)) -> load P
6548 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6549 if (C->isNullValue()) {
6550 LI.setOperand(0, SI->getOperand(1));
6551 return &LI;
6552 }
6553
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006554 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6555 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006556 bool Safe = PN->getParent() == LI.getParent();
6557
6558 // Scan all of the instructions between the PHI and the load to make
6559 // sure there are no instructions that might possibly alter the value
6560 // loaded from the PHI.
6561 if (Safe) {
6562 BasicBlock::iterator I = &LI;
6563 for (--I; !isa<PHINode>(I); --I)
6564 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6565 Safe = false;
6566 break;
6567 }
6568 }
6569
6570 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006571 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006572 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006573 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006574
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006575 if (Safe) {
6576 // Create the PHI.
6577 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6578 InsertNewInstBefore(NewPN, *PN);
6579 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6580
6581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6582 BasicBlock *BB = PN->getIncomingBlock(i);
6583 Value *&TheLoad = LoadMap[BB];
6584 if (TheLoad == 0) {
6585 Value *InVal = PN->getIncomingValue(i);
6586 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6587 InVal->getName()+".val"),
6588 *BB->getTerminator());
6589 }
6590 NewPN->addIncoming(TheLoad, BB);
6591 }
6592 return ReplaceInstUsesWith(LI, NewPN);
6593 }
6594 }
6595 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006596 return 0;
6597}
6598
Chris Lattner72684fe2005-01-31 05:51:45 +00006599/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6600/// when possible.
6601static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6602 User *CI = cast<User>(SI.getOperand(1));
6603 Value *CastOp = CI->getOperand(0);
6604
6605 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6606 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6607 const Type *SrcPTy = SrcTy->getElementType();
6608
6609 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6610 // If the source is an array, the code below will not succeed. Check to
6611 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6612 // constants.
6613 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6614 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6615 if (ASrcTy->getNumElements() != 0) {
6616 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6617 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6618 SrcTy = cast<PointerType>(CastOp->getType());
6619 SrcPTy = SrcTy->getElementType();
6620 }
6621
6622 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006623 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006624 IC.getTargetData().getTypeSize(DestPTy)) {
6625
6626 // Okay, we are casting from one integer or pointer type to another of
6627 // the same size. Instead of casting the pointer before the store, cast
6628 // the value to be stored.
6629 Value *NewCast;
6630 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6631 NewCast = ConstantExpr::getCast(C, SrcPTy);
6632 else
6633 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6634 SrcPTy,
6635 SI.getOperand(0)->getName()+".c"), SI);
6636
6637 return new StoreInst(NewCast, CastOp);
6638 }
6639 }
6640 }
6641 return 0;
6642}
6643
Chris Lattner31f486c2005-01-31 05:36:43 +00006644Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6645 Value *Val = SI.getOperand(0);
6646 Value *Ptr = SI.getOperand(1);
6647
6648 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006649 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006650 ++NumCombined;
6651 return 0;
6652 }
6653
Chris Lattner5997cf92006-02-08 03:25:32 +00006654 // Do really simple DSE, to catch cases where there are several consequtive
6655 // stores to the same location, separated by a few arithmetic operations. This
6656 // situation often occurs with bitfield accesses.
6657 BasicBlock::iterator BBI = &SI;
6658 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6659 --ScanInsts) {
6660 --BBI;
6661
6662 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6663 // Prev store isn't volatile, and stores to the same location?
6664 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6665 ++NumDeadStore;
6666 ++BBI;
6667 EraseInstFromFunction(*PrevSI);
6668 continue;
6669 }
6670 break;
6671 }
6672
6673 // Don't skip over loads or things that can modify memory.
6674 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6675 break;
6676 }
6677
6678
6679 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006680
6681 // store X, null -> turns into 'unreachable' in SimplifyCFG
6682 if (isa<ConstantPointerNull>(Ptr)) {
6683 if (!isa<UndefValue>(Val)) {
6684 SI.setOperand(0, UndefValue::get(Val->getType()));
6685 if (Instruction *U = dyn_cast<Instruction>(Val))
6686 WorkList.push_back(U); // Dropped a use.
6687 ++NumCombined;
6688 }
6689 return 0; // Do not modify these!
6690 }
6691
6692 // store undef, Ptr -> noop
6693 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006694 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006695 ++NumCombined;
6696 return 0;
6697 }
6698
Chris Lattner72684fe2005-01-31 05:51:45 +00006699 // If the pointer destination is a cast, see if we can fold the cast into the
6700 // source instead.
6701 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6702 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6703 return Res;
6704 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6705 if (CE->getOpcode() == Instruction::Cast)
6706 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6707 return Res;
6708
Chris Lattner219175c2005-09-12 23:23:25 +00006709
6710 // If this store is the last instruction in the basic block, and if the block
6711 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006712 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006713 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6714 if (BI->isUnconditional()) {
6715 // Check to see if the successor block has exactly two incoming edges. If
6716 // so, see if the other predecessor contains a store to the same location.
6717 // if so, insert a PHI node (if needed) and move the stores down.
6718 BasicBlock *Dest = BI->getSuccessor(0);
6719
6720 pred_iterator PI = pred_begin(Dest);
6721 BasicBlock *Other = 0;
6722 if (*PI != BI->getParent())
6723 Other = *PI;
6724 ++PI;
6725 if (PI != pred_end(Dest)) {
6726 if (*PI != BI->getParent())
6727 if (Other)
6728 Other = 0;
6729 else
6730 Other = *PI;
6731 if (++PI != pred_end(Dest))
6732 Other = 0;
6733 }
6734 if (Other) { // If only one other pred...
6735 BBI = Other->getTerminator();
6736 // Make sure this other block ends in an unconditional branch and that
6737 // there is an instruction before the branch.
6738 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6739 BBI != Other->begin()) {
6740 --BBI;
6741 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6742
6743 // If this instruction is a store to the same location.
6744 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6745 // Okay, we know we can perform this transformation. Insert a PHI
6746 // node now if we need it.
6747 Value *MergedVal = OtherStore->getOperand(0);
6748 if (MergedVal != SI.getOperand(0)) {
6749 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6750 PN->reserveOperandSpace(2);
6751 PN->addIncoming(SI.getOperand(0), SI.getParent());
6752 PN->addIncoming(OtherStore->getOperand(0), Other);
6753 MergedVal = InsertNewInstBefore(PN, Dest->front());
6754 }
6755
6756 // Advance to a place where it is safe to insert the new store and
6757 // insert it.
6758 BBI = Dest->begin();
6759 while (isa<PHINode>(BBI)) ++BBI;
6760 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6761 OtherStore->isVolatile()), *BBI);
6762
6763 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006764 EraseInstFromFunction(SI);
6765 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006766 ++NumCombined;
6767 return 0;
6768 }
6769 }
6770 }
6771 }
6772
Chris Lattner31f486c2005-01-31 05:36:43 +00006773 return 0;
6774}
6775
6776
Chris Lattner9eef8a72003-06-04 04:46:00 +00006777Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6778 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006779 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006780 BasicBlock *TrueDest;
6781 BasicBlock *FalseDest;
6782 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6783 !isa<Constant>(X)) {
6784 // Swap Destinations and condition...
6785 BI.setCondition(X);
6786 BI.setSuccessor(0, FalseDest);
6787 BI.setSuccessor(1, TrueDest);
6788 return &BI;
6789 }
6790
6791 // Cannonicalize setne -> seteq
6792 Instruction::BinaryOps Op; Value *Y;
6793 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6794 TrueDest, FalseDest)))
6795 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6796 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6797 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6798 std::string Name = I->getName(); I->setName("");
6799 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6800 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006801 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006802 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006803 BI.setSuccessor(0, FalseDest);
6804 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006805 removeFromWorkList(I);
6806 I->getParent()->getInstList().erase(I);
6807 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006808 return &BI;
6809 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006810
Chris Lattner9eef8a72003-06-04 04:46:00 +00006811 return 0;
6812}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006813
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006814Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6815 Value *Cond = SI.getCondition();
6816 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6817 if (I->getOpcode() == Instruction::Add)
6818 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6819 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6820 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006821 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006822 AddRHS));
6823 SI.setOperand(0, I->getOperand(0));
6824 WorkList.push_back(I);
6825 return &SI;
6826 }
6827 }
6828 return 0;
6829}
6830
Chris Lattner6bc98652006-03-05 00:22:33 +00006831/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6832/// is to leave as a vector operation.
6833static bool CheapToScalarize(Value *V, bool isConstant) {
6834 if (isa<ConstantAggregateZero>(V))
6835 return true;
6836 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6837 if (isConstant) return true;
6838 // If all elts are the same, we can extract.
6839 Constant *Op0 = C->getOperand(0);
6840 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6841 if (C->getOperand(i) != Op0)
6842 return false;
6843 return true;
6844 }
6845 Instruction *I = dyn_cast<Instruction>(V);
6846 if (!I) return false;
6847
6848 // Insert element gets simplified to the inserted element or is deleted if
6849 // this is constant idx extract element and its a constant idx insertelt.
6850 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6851 isa<ConstantInt>(I->getOperand(2)))
6852 return true;
6853 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6854 return true;
6855 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6856 if (BO->hasOneUse() &&
6857 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6858 CheapToScalarize(BO->getOperand(1), isConstant)))
6859 return true;
6860
6861 return false;
6862}
6863
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006864/// FindScalarElement - Given a vector and an element number, see if the scalar
6865/// value is already around as a register, for example if it were inserted then
6866/// extracted from the vector.
6867static Value *FindScalarElement(Value *V, unsigned EltNo) {
6868 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6869 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00006870 unsigned Width = PTy->getNumElements();
6871 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006872 return UndefValue::get(PTy->getElementType());
6873
6874 if (isa<UndefValue>(V))
6875 return UndefValue::get(PTy->getElementType());
6876 else if (isa<ConstantAggregateZero>(V))
6877 return Constant::getNullValue(PTy->getElementType());
6878 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6879 return CP->getOperand(EltNo);
6880 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6881 // If this is an insert to a variable element, we don't know what it is.
6882 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6883 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6884
6885 // If this is an insert to the element we are looking for, return the
6886 // inserted value.
6887 if (EltNo == IIElt) return III->getOperand(1);
6888
6889 // Otherwise, the insertelement doesn't modify the value, recurse on its
6890 // vector input.
6891 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00006892 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
6893 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
6894 return FindScalarElement(SVI->getOperand(0), 0);
6895 } else if (ConstantPacked *CP =
6896 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
6897 if (isa<UndefValue>(CP->getOperand(EltNo)))
6898 return UndefValue::get(PTy->getElementType());
6899 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
6900 if (InEl < Width)
6901 return FindScalarElement(SVI->getOperand(0), InEl);
6902 else
6903 return FindScalarElement(SVI->getOperand(1), InEl - Width);
6904 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006905 }
6906
6907 // Otherwise, we don't know.
6908 return 0;
6909}
6910
Robert Bocchinoa8352962006-01-13 22:48:06 +00006911Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006912
Chris Lattner92346c32006-03-31 18:25:14 +00006913 // If packed val is undef, replace extract with scalar undef.
6914 if (isa<UndefValue>(EI.getOperand(0)))
6915 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6916
6917 // If packed val is constant 0, replace extract with scalar 0.
6918 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6919 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6920
Robert Bocchinoa8352962006-01-13 22:48:06 +00006921 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6922 // If packed val is constant with uniform operands, replace EI
6923 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00006924 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00006925 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00006926 if (C->getOperand(i) != op0) {
6927 op0 = 0;
6928 break;
6929 }
6930 if (op0)
6931 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00006932 }
Chris Lattner6bc98652006-03-05 00:22:33 +00006933
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006934 // If extracting a specified index from the vector, see if we can recursively
6935 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00006936 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006937 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6938 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00006939 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00006940
Robert Bocchinoa8352962006-01-13 22:48:06 +00006941 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6942 if (I->hasOneUse()) {
6943 // Push extractelement into predecessor operation if legal and
6944 // profitable to do so
6945 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00006946 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6947 if (CheapToScalarize(BO, isConstantElt)) {
6948 ExtractElementInst *newEI0 =
6949 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6950 EI.getName()+".lhs");
6951 ExtractElementInst *newEI1 =
6952 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6953 EI.getName()+".rhs");
6954 InsertNewInstBefore(newEI0, EI);
6955 InsertNewInstBefore(newEI1, EI);
6956 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6957 }
6958 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00006959 Value *Ptr = InsertCastBefore(I->getOperand(0),
6960 PointerType::get(EI.getType()), EI);
6961 GetElementPtrInst *GEP =
6962 new GetElementPtrInst(Ptr, EI.getOperand(1),
6963 I->getName() + ".gep");
6964 InsertNewInstBefore(GEP, EI);
6965 return new LoadInst(GEP);
Chris Lattner6bc98652006-03-05 00:22:33 +00006966 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6967 // Extracting the inserted element?
6968 if (IE->getOperand(2) == EI.getOperand(1))
6969 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6970 // If the inserted and extracted elements are constants, they must not
Chris Lattner612fa8e2006-03-30 22:02:40 +00006971 // be the same value, extract from the pre-inserted value instead.
6972 if (isa<Constant>(IE->getOperand(2)) &&
6973 isa<Constant>(EI.getOperand(1))) {
6974 AddUsesToWorkList(EI);
6975 EI.setOperand(0, IE->getOperand(0));
6976 return &EI;
6977 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00006978 }
6979 }
6980 return 0;
6981}
6982
Chris Lattner90951862006-04-16 00:51:47 +00006983/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
6984/// elements from either LHS or RHS, return the shuffle mask and true.
6985/// Otherwise, return false.
6986static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
6987 std::vector<Constant*> &Mask) {
6988 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
6989 "Invalid CollectSingleShuffleElements");
6990 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
6991
6992 if (isa<UndefValue>(V)) {
6993 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
6994 return true;
6995 } else if (V == LHS) {
6996 for (unsigned i = 0; i != NumElts; ++i)
6997 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
6998 return true;
6999 } else if (V == RHS) {
7000 for (unsigned i = 0; i != NumElts; ++i)
7001 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7002 return true;
7003 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7004 // If this is an insert of an extract from some other vector, include it.
7005 Value *VecOp = IEI->getOperand(0);
7006 Value *ScalarOp = IEI->getOperand(1);
7007 Value *IdxOp = IEI->getOperand(2);
7008
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007009 if (!isa<ConstantInt>(IdxOp))
7010 return false;
7011 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7012
7013 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7014 // Okay, we can handle this if the vector we are insertinting into is
7015 // transitively ok.
7016 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7017 // If so, update the mask to reflect the inserted undef.
7018 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7019 return true;
7020 }
7021 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7022 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007023 EI->getOperand(0)->getType() == V->getType()) {
7024 unsigned ExtractedIdx =
7025 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007026
7027 // This must be extracting from either LHS or RHS.
7028 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7029 // Okay, we can handle this if the vector we are insertinting into is
7030 // transitively ok.
7031 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7032 // If so, update the mask to reflect the inserted value.
7033 if (EI->getOperand(0) == LHS) {
7034 Mask[InsertedIdx & (NumElts-1)] =
7035 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7036 } else {
7037 assert(EI->getOperand(0) == RHS);
7038 Mask[InsertedIdx & (NumElts-1)] =
7039 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7040
7041 }
7042 return true;
7043 }
7044 }
7045 }
7046 }
7047 }
7048 // TODO: Handle shufflevector here!
7049
7050 return false;
7051}
7052
7053/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7054/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7055/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007056static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007057 Value *&RHS) {
7058 assert(isa<PackedType>(V->getType()) &&
7059 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007060 "Invalid shuffle!");
7061 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7062
7063 if (isa<UndefValue>(V)) {
7064 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7065 return V;
7066 } else if (isa<ConstantAggregateZero>(V)) {
7067 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7068 return V;
7069 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7070 // If this is an insert of an extract from some other vector, include it.
7071 Value *VecOp = IEI->getOperand(0);
7072 Value *ScalarOp = IEI->getOperand(1);
7073 Value *IdxOp = IEI->getOperand(2);
7074
7075 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7076 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7077 EI->getOperand(0)->getType() == V->getType()) {
7078 unsigned ExtractedIdx =
7079 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7080 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7081
7082 // Either the extracted from or inserted into vector must be RHSVec,
7083 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007084 if (EI->getOperand(0) == RHS || RHS == 0) {
7085 RHS = EI->getOperand(0);
7086 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007087 Mask[InsertedIdx & (NumElts-1)] =
7088 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7089 return V;
7090 }
7091
Chris Lattner90951862006-04-16 00:51:47 +00007092 if (VecOp == RHS) {
7093 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007094 // Everything but the extracted element is replaced with the RHS.
7095 for (unsigned i = 0; i != NumElts; ++i) {
7096 if (i != InsertedIdx)
7097 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7098 }
7099 return V;
7100 }
Chris Lattner90951862006-04-16 00:51:47 +00007101
7102 // If this insertelement is a chain that comes from exactly these two
7103 // vectors, return the vector and the effective shuffle.
7104 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7105 return EI->getOperand(0);
7106
Chris Lattner39fac442006-04-15 01:39:45 +00007107 }
7108 }
7109 }
Chris Lattner90951862006-04-16 00:51:47 +00007110 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007111
7112 // Otherwise, can't do anything fancy. Return an identity vector.
7113 for (unsigned i = 0; i != NumElts; ++i)
7114 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7115 return V;
7116}
7117
7118Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7119 Value *VecOp = IE.getOperand(0);
7120 Value *ScalarOp = IE.getOperand(1);
7121 Value *IdxOp = IE.getOperand(2);
7122
7123 // If the inserted element was extracted from some other vector, and if the
7124 // indexes are constant, try to turn this into a shufflevector operation.
7125 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7126 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7127 EI->getOperand(0)->getType() == IE.getType()) {
7128 unsigned NumVectorElts = IE.getType()->getNumElements();
7129 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7130 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7131
7132 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7133 return ReplaceInstUsesWith(IE, VecOp);
7134
7135 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7136 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7137
7138 // If we are extracting a value from a vector, then inserting it right
7139 // back into the same place, just use the input vector.
7140 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7141 return ReplaceInstUsesWith(IE, VecOp);
7142
7143 // We could theoretically do this for ANY input. However, doing so could
7144 // turn chains of insertelement instructions into a chain of shufflevector
7145 // instructions, and right now we do not merge shufflevectors. As such,
7146 // only do this in a situation where it is clear that there is benefit.
7147 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7148 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7149 // the values of VecOp, except then one read from EIOp0.
7150 // Build a new shuffle mask.
7151 std::vector<Constant*> Mask;
7152 if (isa<UndefValue>(VecOp))
7153 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7154 else {
7155 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7156 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7157 NumVectorElts));
7158 }
7159 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7160 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7161 ConstantPacked::get(Mask));
7162 }
7163
7164 // If this insertelement isn't used by some other insertelement, turn it
7165 // (and any insertelements it points to), into one big shuffle.
7166 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7167 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007168 Value *RHS = 0;
7169 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7170 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7171 // We now have a shuffle of LHS, RHS, Mask.
7172 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007173 }
7174 }
7175 }
7176
7177 return 0;
7178}
7179
7180
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007181Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7182 Value *LHS = SVI.getOperand(0);
7183 Value *RHS = SVI.getOperand(1);
7184 Constant *Mask = cast<Constant>(SVI.getOperand(2));
7185
7186 bool MadeChange = false;
7187
7188 if (isa<UndefValue>(Mask))
7189 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7190
Chris Lattner39fac442006-04-15 01:39:45 +00007191 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7192 // the undef, change them to undefs.
7193
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007194 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
7195 if (LHS == RHS) {
7196 if (isa<UndefValue>(LHS)) {
7197 // shuffle(undef,undef,mask) -> undef.
7198 return ReplaceInstUsesWith(SVI, LHS);
7199 }
7200
7201 if (!isa<ConstantAggregateZero>(Mask)) {
7202 // Remap any references to RHS to use LHS.
7203 ConstantPacked *CP = cast<ConstantPacked>(Mask);
7204 std::vector<Constant*> Elts;
7205 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7206 Elts.push_back(CP->getOperand(i));
7207 if (isa<UndefValue>(CP->getOperand(i)))
7208 continue;
7209 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7210 if (MV >= e)
7211 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
7212 }
7213 Mask = ConstantPacked::get(Elts);
7214 }
7215 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7216 SVI.setOperand(2, Mask);
7217 MadeChange = true;
7218 }
7219
Chris Lattner34cebe72006-04-16 00:03:56 +00007220 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7221 if (isa<UndefValue>(LHS)) {
7222 // shuffle(undef,x,<0,0,0,0>) -> undef.
7223 if (isa<ConstantAggregateZero>(Mask))
7224 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7225
7226 ConstantPacked *CPM = cast<ConstantPacked>(Mask);
7227 std::vector<Constant*> Elts;
7228 for (unsigned i = 0, e = CPM->getNumOperands(); i != e; ++i) {
7229 if (isa<UndefValue>(CPM->getOperand(i)))
7230 Elts.push_back(CPM->getOperand(i));
7231 else {
7232 unsigned EltNo = cast<ConstantUInt>(CPM->getOperand(i))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007233 if (EltNo >= e)
7234 Elts.push_back(ConstantUInt::get(Type::UIntTy, EltNo-e));
Chris Lattner34cebe72006-04-16 00:03:56 +00007235 else // Referring to the undef.
7236 Elts.push_back(UndefValue::get(Type::UIntTy));
7237 }
7238 }
7239 return new ShuffleVectorInst(RHS, LHS, ConstantPacked::get(Elts));
7240 }
7241
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007242 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
7243 bool isLHSID = true, isRHSID = true;
7244
7245 // Analyze the shuffle.
7246 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7247 if (isa<UndefValue>(CP->getOperand(i)))
7248 continue;
7249 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7250
7251 // Is this an identity shuffle of the LHS value?
7252 isLHSID &= (MV == i);
7253
7254 // Is this an identity shuffle of the RHS value?
7255 isRHSID &= (MV-e == i);
7256 }
7257
7258 // Eliminate identity shuffles.
7259 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7260 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7261 }
7262
7263 return MadeChange ? &SVI : 0;
7264}
7265
7266
Robert Bocchinoa8352962006-01-13 22:48:06 +00007267
Chris Lattner99f48c62002-09-02 04:59:56 +00007268void InstCombiner::removeFromWorkList(Instruction *I) {
7269 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7270 WorkList.end());
7271}
7272
Chris Lattner39c98bb2004-12-08 23:43:58 +00007273
7274/// TryToSinkInstruction - Try to move the specified instruction from its
7275/// current block into the beginning of DestBlock, which can only happen if it's
7276/// safe to move the instruction past all of the instructions between it and the
7277/// end of its block.
7278static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7279 assert(I->hasOneUse() && "Invariants didn't hold!");
7280
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007281 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7282 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007283
Chris Lattner39c98bb2004-12-08 23:43:58 +00007284 // Do not sink alloca instructions out of the entry block.
7285 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7286 return false;
7287
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007288 // We can only sink load instructions if there is nothing between the load and
7289 // the end of block that could change the value.
7290 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007291 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7292 Scan != E; ++Scan)
7293 if (Scan->mayWriteToMemory())
7294 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007295 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007296
7297 BasicBlock::iterator InsertPos = DestBlock->begin();
7298 while (isa<PHINode>(InsertPos)) ++InsertPos;
7299
Chris Lattner9f269e42005-08-08 19:11:57 +00007300 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007301 ++NumSunkInst;
7302 return true;
7303}
7304
Chris Lattner113f4f42002-06-25 16:13:24 +00007305bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00007306 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00007307 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00007308
Chris Lattner4ed40f72005-07-07 20:40:38 +00007309 {
7310 // Populate the worklist with the reachable instructions.
7311 std::set<BasicBlock*> Visited;
7312 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
7313 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
7314 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
7315 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00007316
Chris Lattner4ed40f72005-07-07 20:40:38 +00007317 // Do a quick scan over the function. If we find any blocks that are
7318 // unreachable, remove any instructions inside of them. This prevents
7319 // the instcombine code from having to deal with some bad special cases.
7320 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7321 if (!Visited.count(BB)) {
7322 Instruction *Term = BB->getTerminator();
7323 while (Term != BB->begin()) { // Remove instrs bottom-up
7324 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00007325
Chris Lattner4ed40f72005-07-07 20:40:38 +00007326 DEBUG(std::cerr << "IC: DCE: " << *I);
7327 ++NumDeadInst;
7328
7329 if (!I->use_empty())
7330 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7331 I->eraseFromParent();
7332 }
7333 }
7334 }
Chris Lattnerca081252001-12-14 16:52:21 +00007335
7336 while (!WorkList.empty()) {
7337 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7338 WorkList.pop_back();
7339
Misha Brukman632df282002-10-29 23:06:16 +00007340 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00007341 // Check to see if we can DIE the instruction...
7342 if (isInstructionTriviallyDead(I)) {
7343 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007344 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00007345 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00007346 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007347
Chris Lattnercd517ff2005-01-28 19:32:01 +00007348 DEBUG(std::cerr << "IC: DCE: " << *I);
7349
7350 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007351 removeFromWorkList(I);
7352 continue;
7353 }
Chris Lattner99f48c62002-09-02 04:59:56 +00007354
Misha Brukman632df282002-10-29 23:06:16 +00007355 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00007356 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007357 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00007358 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007359 cast<Constant>(Ptr)->isNullValue() &&
7360 !isa<ConstantPointerNull>(C) &&
7361 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00007362 // If this is a constant expr gep that is effectively computing an
7363 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
7364 bool isFoldableGEP = true;
7365 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
7366 if (!isa<ConstantInt>(I->getOperand(i)))
7367 isFoldableGEP = false;
7368 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00007369 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00007370 std::vector<Value*>(I->op_begin()+1, I->op_end()));
7371 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00007372 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00007373 C = ConstantExpr::getCast(C, I->getType());
7374 }
7375 }
7376
Chris Lattnercd517ff2005-01-28 19:32:01 +00007377 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7378
Chris Lattner99f48c62002-09-02 04:59:56 +00007379 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00007380 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00007381 ReplaceInstUsesWith(*I, C);
7382
Chris Lattner99f48c62002-09-02 04:59:56 +00007383 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007384 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00007385 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007386 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00007387 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007388
Chris Lattner39c98bb2004-12-08 23:43:58 +00007389 // See if we can trivially sink this instruction to a successor basic block.
7390 if (I->hasOneUse()) {
7391 BasicBlock *BB = I->getParent();
7392 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7393 if (UserParent != BB) {
7394 bool UserIsSuccessor = false;
7395 // See if the user is one of our successors.
7396 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7397 if (*SI == UserParent) {
7398 UserIsSuccessor = true;
7399 break;
7400 }
7401
7402 // If the user is one of our immediate successors, and if that successor
7403 // only has us as a predecessors (we'd have to split the critical edge
7404 // otherwise), we can keep going.
7405 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7406 next(pred_begin(UserParent)) == pred_end(UserParent))
7407 // Okay, the CFG is simple enough, try to sink this instruction.
7408 Changed |= TryToSinkInstruction(I, UserParent);
7409 }
7410 }
7411
Chris Lattnerca081252001-12-14 16:52:21 +00007412 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007413 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00007414 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00007415 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00007416 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007417 DEBUG(std::cerr << "IC: Old = " << *I
7418 << " New = " << *Result);
7419
Chris Lattner396dbfe2004-06-09 05:08:07 +00007420 // Everything uses the new instruction now.
7421 I->replaceAllUsesWith(Result);
7422
7423 // Push the new instruction and any users onto the worklist.
7424 WorkList.push_back(Result);
7425 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007426
7427 // Move the name to the new instruction first...
7428 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00007429 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007430
7431 // Insert the new instruction into the basic block...
7432 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00007433 BasicBlock::iterator InsertPos = I;
7434
7435 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7436 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7437 ++InsertPos;
7438
7439 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007440
Chris Lattner63d75af2004-05-01 23:27:23 +00007441 // Make sure that we reprocess all operands now that we reduced their
7442 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00007443 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7444 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7445 WorkList.push_back(OpI);
7446
Chris Lattner396dbfe2004-06-09 05:08:07 +00007447 // Instructions can end up on the worklist more than once. Make sure
7448 // we do not process an instruction that has been deleted.
7449 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007450
7451 // Erase the old instruction.
7452 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00007453 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007454 DEBUG(std::cerr << "IC: MOD = " << *I);
7455
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007456 // If the instruction was modified, it's possible that it is now dead.
7457 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00007458 if (isInstructionTriviallyDead(I)) {
7459 // Make sure we process all operands now that we are reducing their
7460 // use counts.
7461 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7462 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7463 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007464
Chris Lattner63d75af2004-05-01 23:27:23 +00007465 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00007466 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007467 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00007468 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00007469 } else {
7470 WorkList.push_back(Result);
7471 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007472 }
Chris Lattner053c0932002-05-14 15:24:07 +00007473 }
Chris Lattner260ab202002-04-18 17:39:14 +00007474 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00007475 }
7476 }
7477
Chris Lattner260ab202002-04-18 17:39:14 +00007478 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00007479}
7480
Brian Gaeke38b79e82004-07-27 17:43:21 +00007481FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00007482 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00007483}
Brian Gaeke960707c2003-11-11 22:41:34 +00007484