blob: dd8a63053c72b6950dcfe448326726a122008783 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerc597b8a2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner8427bff2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000058
Chris Lattner260ab202002-04-18 17:39:14 +000059namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner5997cf92006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000065
Chris Lattnerc8e66542002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000071
Chris Lattner51ea1272004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner2590e512006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner51ea1272004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
90
Chris Lattner99f48c62002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000093 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000095
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000099 }
100
Chris Lattner69193f92004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000109 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner0798af32005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattner260ab202002-04-18 17:39:14 +0000141
142 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000143 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144
Chris Lattner970c33a2003-06-19 17:00:31 +0000145 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000146 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000147 bool transformConstExprCastCall(CallSite CS);
148
Chris Lattner69193f92004-04-05 01:30:19 +0000149 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 // InsertNewInstBefore - insert an instruction New before instruction Old
151 // in the program. Add the new instruction to the worklist.
152 //
Chris Lattner623826c2004-09-28 21:48:02 +0000153 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000154 assert(New && New->getParent() == 0 &&
155 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000156 BasicBlock *BB = Old.getParent();
157 BB->getInstList().insert(&Old, New); // Insert inst
158 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000159 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 }
161
Chris Lattner7e794272004-09-24 15:21:34 +0000162 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
163 /// This also adds the cast to the worklist. Finally, this returns the
164 /// cast.
165 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
166 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000167
Chris Lattner7e794272004-09-24 15:21:34 +0000168 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
169 WorkList.push_back(C);
170 return C;
171 }
172
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000173 // ReplaceInstUsesWith - This method is to be used when an instruction is
174 // found to be dead, replacable with another preexisting expression. Here
175 // we add all uses of I to the worklist, replace all uses of I with the new
176 // value, then return I, so that the inst combiner will know that I was
177 // modified.
178 //
179 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000180 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000181 if (&I != V) {
182 I.replaceAllUsesWith(V);
183 return &I;
184 } else {
185 // If we are replacing the instruction with itself, this must be in a
186 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000187 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000188 return &I;
189 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000190 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000191
Chris Lattner2590e512006-02-07 06:56:34 +0000192 // UpdateValueUsesWith - This method is to be used when an value is
193 // found to be replacable with another preexisting expression or was
194 // updated. Here we add all uses of I to the worklist, replace all uses of
195 // I with the new value (unless the instruction was just updated), then
196 // return true, so that the inst combiner will know that I was modified.
197 //
198 bool UpdateValueUsesWith(Value *Old, Value *New) {
199 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
200 if (Old != New)
201 Old->replaceAllUsesWith(New);
202 if (Instruction *I = dyn_cast<Instruction>(Old))
203 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000204 if (Instruction *I = dyn_cast<Instruction>(New))
205 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000206 return true;
207 }
208
Chris Lattner51ea1272004-02-28 05:22:00 +0000209 // EraseInstFromFunction - When dealing with an instruction that has side
210 // effects or produces a void value, we can't rely on DCE to delete the
211 // instruction. Instead, visit methods should return the value returned by
212 // this function.
213 Instruction *EraseInstFromFunction(Instruction &I) {
214 assert(I.use_empty() && "Cannot erase instruction that is used!");
215 AddUsesToWorkList(I);
216 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000217 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000218 return 0; // Don't do anything with FI
219 }
220
Chris Lattner3ac7c262003-08-13 20:16:26 +0000221 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000222 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
223 /// InsertBefore instruction. This is specialized a bit to avoid inserting
224 /// casts that are known to not do anything...
225 ///
226 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
227 Instruction *InsertBefore);
228
Chris Lattner7fb29e12003-03-11 00:12:48 +0000229 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000230 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000231 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000232
Chris Lattner0157e7f2006-02-11 09:31:47 +0000233 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
234 uint64_t &KnownZero, uint64_t &KnownOne,
235 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000236
237 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
238 // PHI node as operand #0, see if we can fold the instruction into the PHI
239 // (which is only possible if all operands to the PHI are constants).
240 Instruction *FoldOpIntoPhi(Instruction &I);
241
Chris Lattner7515cab2004-11-14 19:13:23 +0000242 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
243 // operator and they all are only used by the PHI, PHI together their
244 // inputs, and do the operation once, to the result of the PHI.
245 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
246
Chris Lattnerba1cb382003-09-19 17:17:26 +0000247 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
248 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000249
250 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
251 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000252 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
253 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000254 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000255 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000256
Chris Lattnerc8b70922002-07-26 21:12:46 +0000257 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000258}
259
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000261// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000262static unsigned getComplexity(Value *V) {
263 if (isa<Instruction>(V)) {
264 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000265 return 3;
266 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000268 if (isa<Argument>(V)) return 3;
269 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270}
Chris Lattner260ab202002-04-18 17:39:14 +0000271
Chris Lattner7fb29e12003-03-11 00:12:48 +0000272// isOnlyUse - Return true if this instruction will be deleted if we stop using
273// it.
274static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000275 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000276}
277
Chris Lattnere79e8542004-02-23 06:38:22 +0000278// getPromotedType - Return the specified type promoted as it would be to pass
279// though a va_arg area...
280static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000281 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000282 case Type::SByteTyID:
283 case Type::ShortTyID: return Type::IntTy;
284 case Type::UByteTyID:
285 case Type::UShortTyID: return Type::UIntTy;
286 case Type::FloatTyID: return Type::DoubleTy;
287 default: return Ty;
288 }
289}
290
Chris Lattner567b81f2005-09-13 00:40:14 +0000291/// isCast - If the specified operand is a CastInst or a constant expr cast,
292/// return the operand value, otherwise return null.
293static Value *isCast(Value *V) {
294 if (CastInst *I = dyn_cast<CastInst>(V))
295 return I->getOperand(0);
296 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
297 if (CE->getOpcode() == Instruction::Cast)
298 return CE->getOperand(0);
299 return 0;
300}
301
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000302// SimplifyCommutative - This performs a few simplifications for commutative
303// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000304//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000305// 1. Order operands such that they are listed from right (least complex) to
306// left (most complex). This puts constants before unary operators before
307// binary operators.
308//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000309// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
310// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000311//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000312bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000313 bool Changed = false;
314 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
315 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000316
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000317 if (!I.isAssociative()) return Changed;
318 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000319 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
320 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
321 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000322 Constant *Folded = ConstantExpr::get(I.getOpcode(),
323 cast<Constant>(I.getOperand(1)),
324 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000325 I.setOperand(0, Op->getOperand(0));
326 I.setOperand(1, Folded);
327 return true;
328 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
329 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
330 isOnlyUse(Op) && isOnlyUse(Op1)) {
331 Constant *C1 = cast<Constant>(Op->getOperand(1));
332 Constant *C2 = cast<Constant>(Op1->getOperand(1));
333
334 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000335 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000336 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
337 Op1->getOperand(0),
338 Op1->getName(), &I);
339 WorkList.push_back(New);
340 I.setOperand(0, New);
341 I.setOperand(1, Folded);
342 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000343 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000344 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000345 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000346}
Chris Lattnerca081252001-12-14 16:52:21 +0000347
Chris Lattnerbb74e222003-03-10 23:06:50 +0000348// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
349// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000350//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000351static inline Value *dyn_castNegVal(Value *V) {
352 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000353 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000354
Chris Lattner9ad0d552004-12-14 20:08:06 +0000355 // Constants can be considered to be negated values if they can be folded.
356 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
357 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000358 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000359}
360
Chris Lattnerbb74e222003-03-10 23:06:50 +0000361static inline Value *dyn_castNotVal(Value *V) {
362 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000363 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000364
365 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000366 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000367 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000368 return 0;
369}
370
Chris Lattner7fb29e12003-03-11 00:12:48 +0000371// dyn_castFoldableMul - If this value is a multiply that can be folded into
372// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000373// non-constant operand of the multiply, and set CST to point to the multiplier.
374// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000375//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000376static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000377 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000378 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000379 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000380 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000381 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000382 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000383 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000384 // The multiplier is really 1 << CST.
385 Constant *One = ConstantInt::get(V->getType(), 1);
386 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
387 return I->getOperand(0);
388 }
389 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000390 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000391}
Chris Lattner31ae8632002-08-14 17:51:49 +0000392
Chris Lattner0798af32005-01-13 20:14:25 +0000393/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
394/// expression, return it.
395static User *dyn_castGetElementPtr(Value *V) {
396 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
397 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
398 if (CE->getOpcode() == Instruction::GetElementPtr)
399 return cast<User>(V);
400 return false;
401}
402
Chris Lattner623826c2004-09-28 21:48:02 +0000403// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000404static ConstantInt *AddOne(ConstantInt *C) {
405 return cast<ConstantInt>(ConstantExpr::getAdd(C,
406 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000407}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000408static ConstantInt *SubOne(ConstantInt *C) {
409 return cast<ConstantInt>(ConstantExpr::getSub(C,
410 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000411}
412
Chris Lattner0157e7f2006-02-11 09:31:47 +0000413/// GetConstantInType - Return a ConstantInt with the specified type and value.
414///
Chris Lattneree0f2802006-02-12 02:07:56 +0000415static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000416 if (Ty->isUnsigned())
417 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000418 else if (Ty->getTypeID() == Type::BoolTyID)
419 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000420 int64_t SVal = Val;
421 SVal <<= 64-Ty->getPrimitiveSizeInBits();
422 SVal >>= 64-Ty->getPrimitiveSizeInBits();
423 return ConstantSInt::get(Ty, SVal);
424}
425
426
Chris Lattner4534dd592006-02-09 07:38:58 +0000427/// ComputeMaskedBits - Determine which of the bits specified in Mask are
428/// known to be either zero or one and return them in the KnownZero/KnownOne
429/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
430/// processing.
431static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
432 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000433 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
434 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000435 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000436 // optimized based on the contradictory assumption that it is non-zero.
437 // Because instcombine aggressively folds operations with undef args anyway,
438 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000439 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
440 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000441 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000442 KnownZero = ~KnownOne & Mask;
443 return;
444 }
445
446 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000447 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000448 return; // Limit search depth.
449
450 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000451 Instruction *I = dyn_cast<Instruction>(V);
452 if (!I) return;
453
454 switch (I->getOpcode()) {
455 case Instruction::And:
456 // If either the LHS or the RHS are Zero, the result is zero.
457 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
458 Mask &= ~KnownZero;
459 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
460 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
461 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
462
463 // Output known-1 bits are only known if set in both the LHS & RHS.
464 KnownOne &= KnownOne2;
465 // Output known-0 are known to be clear if zero in either the LHS | RHS.
466 KnownZero |= KnownZero2;
467 return;
468 case Instruction::Or:
469 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
470 Mask &= ~KnownOne;
471 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
472 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
473 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
474
475 // Output known-0 bits are only known if clear in both the LHS & RHS.
476 KnownZero &= KnownZero2;
477 // Output known-1 are known to be set if set in either the LHS | RHS.
478 KnownOne |= KnownOne2;
479 return;
480 case Instruction::Xor: {
481 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
482 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
483 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
484 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
485
486 // Output known-0 bits are known if clear or set in both the LHS & RHS.
487 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
488 // Output known-1 are known to be set if set in only one of the LHS, RHS.
489 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
490 KnownZero = KnownZeroOut;
491 return;
492 }
493 case Instruction::Select:
494 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
495 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
496 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
497 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
498
499 // Only known if known in both the LHS and RHS.
500 KnownOne &= KnownOne2;
501 KnownZero &= KnownZero2;
502 return;
503 case Instruction::Cast: {
504 const Type *SrcTy = I->getOperand(0)->getType();
505 if (!SrcTy->isIntegral()) return;
506
507 // If this is an integer truncate or noop, just look in the input.
508 if (SrcTy->getPrimitiveSizeInBits() >=
509 I->getType()->getPrimitiveSizeInBits()) {
510 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000511 return;
512 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000513
Chris Lattner0157e7f2006-02-11 09:31:47 +0000514 // Sign or Zero extension. Compute the bits in the result that are not
515 // present in the input.
516 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
517 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000518
Chris Lattner0157e7f2006-02-11 09:31:47 +0000519 // Handle zero extension.
520 if (!SrcTy->isSigned()) {
521 Mask &= SrcTy->getIntegralTypeMask();
522 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
523 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
524 // The top bits are known to be zero.
525 KnownZero |= NewBits;
526 } else {
527 // Sign extension.
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?");
Chris Lattner92a68652006-02-07 08:05:22 +0000531
Chris Lattner0157e7f2006-02-11 09:31:47 +0000532 // If the sign bit of the input is known set or clear, then we know the
533 // top bits of the result.
534 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
535 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000536 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000537 KnownOne &= ~NewBits;
538 } else if (KnownOne & InSignBit) { // Input sign bit known set
539 KnownOne |= NewBits;
540 KnownZero &= ~NewBits;
541 } else { // Input sign bit unknown
542 KnownZero &= ~NewBits;
543 KnownOne &= ~NewBits;
544 }
545 }
546 return;
547 }
548 case Instruction::Shl:
549 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
550 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
551 Mask >>= SA->getValue();
552 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
553 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
554 KnownZero <<= SA->getValue();
555 KnownOne <<= SA->getValue();
556 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
557 return;
558 }
559 break;
560 case Instruction::Shr:
561 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
562 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
563 // Compute the new bits that are at the top now.
564 uint64_t HighBits = (1ULL << SA->getValue())-1;
565 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
566
567 if (I->getType()->isUnsigned()) { // Unsigned shift right.
568 Mask <<= SA->getValue();
569 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
570 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
571 KnownZero >>= SA->getValue();
572 KnownOne >>= SA->getValue();
573 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000574 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000575 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
581 // Handle the sign bits.
582 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
583 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
584
585 if (KnownZero & SignBit) { // New bits are known zero.
586 KnownZero |= HighBits;
587 } else if (KnownOne & SignBit) { // New bits are known one.
588 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000589 }
590 }
591 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000592 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000593 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000594 }
Chris Lattner92a68652006-02-07 08:05:22 +0000595}
596
597/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
598/// this predicate to simplify operations downstream. Mask is known to be zero
599/// for bits that V cannot have.
600static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000601 uint64_t KnownZero, KnownOne;
602 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000605}
606
Chris Lattner0157e7f2006-02-11 09:31:47 +0000607/// ShrinkDemandedConstant - Check to see if the specified operand of the
608/// specified instruction is a constant integer. If so, check to see if there
609/// are any bits set in the constant that are not demanded. If so, shrink the
610/// constant and return true.
611static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
612 uint64_t Demanded) {
613 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
614 if (!OpC) return false;
615
616 // If there are no bits set that aren't demanded, nothing to do.
617 if ((~Demanded & OpC->getZExtValue()) == 0)
618 return false;
619
620 // This is producing any bits that are not needed, shrink the RHS.
621 uint64_t Val = Demanded & OpC->getZExtValue();
622 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
623 return true;
624}
625
Chris Lattneree0f2802006-02-12 02:07:56 +0000626// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
627// set of known zero and one bits, compute the maximum and minimum values that
628// could have the specified known zero and known one bits, returning them in
629// min/max.
630static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
631 uint64_t KnownZero,
632 uint64_t KnownOne,
633 int64_t &Min, int64_t &Max) {
634 uint64_t TypeBits = Ty->getIntegralTypeMask();
635 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
636
637 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
638
639 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
640 // bit if it is unknown.
641 Min = KnownOne;
642 Max = KnownOne|UnknownBits;
643
644 if (SignBit & UnknownBits) { // Sign bit is unknown
645 Min |= SignBit;
646 Max &= ~SignBit;
647 }
648
649 // Sign extend the min/max values.
650 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
651 Min = (Min << ShAmt) >> ShAmt;
652 Max = (Max << ShAmt) >> ShAmt;
653}
654
655// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
656// a set of known zero and one bits, compute the maximum and minimum values that
657// could have the specified known zero and known one bits, returning them in
658// min/max.
659static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
660 uint64_t KnownZero,
661 uint64_t KnownOne,
662 uint64_t &Min,
663 uint64_t &Max) {
664 uint64_t TypeBits = Ty->getIntegralTypeMask();
665 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
666
667 // The minimum value is when the unknown bits are all zeros.
668 Min = KnownOne;
669 // The maximum value is when the unknown bits are all ones.
670 Max = KnownOne|UnknownBits;
671}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000672
673
674/// SimplifyDemandedBits - Look at V. At this point, we know that only the
675/// DemandedMask bits of the result of V are ever used downstream. If we can
676/// use this information to simplify V, do so and return true. Otherwise,
677/// analyze the expression and return a mask of KnownOne and KnownZero bits for
678/// the expression (used to simplify the caller). The KnownZero/One bits may
679/// only be accurate for those bits in the DemandedMask.
680bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
681 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000682 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000683 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
684 // We know all of the bits for a constant!
685 KnownOne = CI->getZExtValue() & DemandedMask;
686 KnownZero = ~KnownOne & DemandedMask;
687 return false;
688 }
689
690 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000691 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000692 if (Depth != 0) { // Not at the root.
693 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
694 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000695 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000696 }
Chris Lattner2590e512006-02-07 06:56:34 +0000697 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000698 // just set the DemandedMask to all bits.
699 DemandedMask = V->getType()->getIntegralTypeMask();
700 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000701 if (V != UndefValue::get(V->getType()))
702 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
703 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000704 } else if (Depth == 6) { // Limit search depth.
705 return false;
706 }
707
708 Instruction *I = dyn_cast<Instruction>(V);
709 if (!I) return false; // Only analyze instructions.
710
Chris Lattner0157e7f2006-02-11 09:31:47 +0000711 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000712 switch (I->getOpcode()) {
713 default: break;
714 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000715 // If either the LHS or the RHS are Zero, the result is zero.
716 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
717 KnownZero, KnownOne, Depth+1))
718 return true;
719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
720
721 // If something is known zero on the RHS, the bits aren't demanded on the
722 // LHS.
723 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
724 KnownZero2, KnownOne2, Depth+1))
725 return true;
726 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
727
728 // If all of the demanded bits are known one on one side, return the other.
729 // These bits cannot contribute to the result of the 'and'.
730 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
731 return UpdateValueUsesWith(I, I->getOperand(0));
732 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
733 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000734
735 // If all of the demanded bits in the inputs are known zeros, return zero.
736 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
737 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
738
Chris Lattner0157e7f2006-02-11 09:31:47 +0000739 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000740 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000741 return UpdateValueUsesWith(I, I);
742
743 // Output known-1 bits are only known if set in both the LHS & RHS.
744 KnownOne &= KnownOne2;
745 // Output known-0 are known to be clear if zero in either the LHS | RHS.
746 KnownZero |= KnownZero2;
747 break;
748 case Instruction::Or:
749 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
750 KnownZero, KnownOne, Depth+1))
751 return true;
752 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
753 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
754 KnownZero2, KnownOne2, Depth+1))
755 return true;
756 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
757
758 // If all of the demanded bits are known zero on one side, return the other.
759 // These bits cannot contribute to the result of the 'or'.
760 if ((DemandedMask & ~KnownOne2 & KnownZero) == DemandedMask & ~KnownOne2)
761 return UpdateValueUsesWith(I, I->getOperand(0));
762 if ((DemandedMask & ~KnownOne & KnownZero2) == DemandedMask & ~KnownOne)
763 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000764
765 // If all of the potentially set bits on one side are known to be set on
766 // the other side, just use the 'other' side.
767 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
768 (DemandedMask & (~KnownZero)))
769 return UpdateValueUsesWith(I, I->getOperand(0));
770 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
771 (DemandedMask & (~KnownZero2)))
772 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000773
774 // If the RHS is a constant, see if we can simplify it.
775 if (ShrinkDemandedConstant(I, 1, DemandedMask))
776 return UpdateValueUsesWith(I, I);
777
778 // Output known-0 bits are only known if clear in both the LHS & RHS.
779 KnownZero &= KnownZero2;
780 // Output known-1 are known to be set if set in either the LHS | RHS.
781 KnownOne |= KnownOne2;
782 break;
783 case Instruction::Xor: {
784 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
785 KnownZero, KnownOne, Depth+1))
786 return true;
787 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
788 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
789 KnownZero2, KnownOne2, Depth+1))
790 return true;
791 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
792
793 // If all of the demanded bits are known zero on one side, return the other.
794 // These bits cannot contribute to the result of the 'xor'.
795 if ((DemandedMask & KnownZero) == DemandedMask)
796 return UpdateValueUsesWith(I, I->getOperand(0));
797 if ((DemandedMask & KnownZero2) == DemandedMask)
798 return UpdateValueUsesWith(I, I->getOperand(1));
799
800 // Output known-0 bits are known if clear or set in both the LHS & RHS.
801 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
802 // Output known-1 are known to be set if set in only one of the LHS, RHS.
803 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
804
805 // If all of the unknown bits are known to be zero on one side or the other
806 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000807 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000808 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
809 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
810 Instruction *Or =
811 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
812 I->getName());
813 InsertNewInstBefore(Or, *I);
814 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000815 }
816 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000817
Chris Lattner5b2edb12006-02-12 08:02:11 +0000818 // If all of the demanded bits on one side are known, and all of the set
819 // bits on that side are also known to be set on the other side, turn this
820 // into an AND, as we know the bits will be cleared.
821 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
822 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
823 if ((KnownOne & KnownOne2) == KnownOne) {
824 Constant *AndC = GetConstantInType(I->getType(),
825 ~KnownOne & DemandedMask);
826 Instruction *And =
827 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
828 InsertNewInstBefore(And, *I);
829 return UpdateValueUsesWith(I, And);
830 }
831 }
832
Chris Lattner0157e7f2006-02-11 09:31:47 +0000833 // If the RHS is a constant, see if we can simplify it.
834 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
835 if (ShrinkDemandedConstant(I, 1, DemandedMask))
836 return UpdateValueUsesWith(I, I);
837
838 KnownZero = KnownZeroOut;
839 KnownOne = KnownOneOut;
840 break;
841 }
842 case Instruction::Select:
843 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
844 KnownZero, KnownOne, Depth+1))
845 return true;
846 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
847 KnownZero2, KnownOne2, Depth+1))
848 return true;
849 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
850 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
851
852 // If the operands are constants, see if we can simplify them.
853 if (ShrinkDemandedConstant(I, 1, DemandedMask))
854 return UpdateValueUsesWith(I, I);
855 if (ShrinkDemandedConstant(I, 2, DemandedMask))
856 return UpdateValueUsesWith(I, I);
857
858 // Only known if known in both the LHS and RHS.
859 KnownOne &= KnownOne2;
860 KnownZero &= KnownZero2;
861 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000862 case Instruction::Cast: {
863 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000864 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000865
Chris Lattner0157e7f2006-02-11 09:31:47 +0000866 // If this is an integer truncate or noop, just look in the input.
867 if (SrcTy->getPrimitiveSizeInBits() >=
868 I->getType()->getPrimitiveSizeInBits()) {
869 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
870 KnownZero, KnownOne, Depth+1))
871 return true;
872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
873 break;
874 }
875
876 // Sign or Zero extension. Compute the bits in the result that are not
877 // present in the input.
878 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
879 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
880
881 // Handle zero extension.
882 if (!SrcTy->isSigned()) {
883 DemandedMask &= SrcTy->getIntegralTypeMask();
884 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
885 KnownZero, KnownOne, Depth+1))
886 return true;
887 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
888 // The top bits are known to be zero.
889 KnownZero |= NewBits;
890 } else {
891 // Sign extension.
892 if (SimplifyDemandedBits(I->getOperand(0),
893 DemandedMask & SrcTy->getIntegralTypeMask(),
894 KnownZero, KnownOne, Depth+1))
895 return true;
896 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
897
898 // If the sign bit of the input is known set or clear, then we know the
899 // top bits of the result.
900 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
Chris Lattner2590e512006-02-07 06:56:34 +0000901
Chris Lattner0157e7f2006-02-11 09:31:47 +0000902 // If the input sign bit is known zero, or if the NewBits are not demanded
903 // convert this into a zero extension.
904 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +0000905 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000906 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000907 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000908 I->getOperand(0)->getName());
909 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000910 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +0000911 NewVal = new CastInst(NewVal, I->getType(), I->getName());
912 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000913 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000914 } else if (KnownOne & InSignBit) { // Input sign bit known set
915 KnownOne |= NewBits;
916 KnownZero &= ~NewBits;
917 } else { // Input sign bit unknown
918 KnownZero &= ~NewBits;
919 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +0000920 }
Chris Lattner2590e512006-02-07 06:56:34 +0000921 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000922 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000923 }
Chris Lattner2590e512006-02-07 06:56:34 +0000924 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000925 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
926 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
927 KnownZero, KnownOne, Depth+1))
928 return true;
929 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
930 KnownZero <<= SA->getValue();
931 KnownOne <<= SA->getValue();
932 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
933 }
Chris Lattner2590e512006-02-07 06:56:34 +0000934 break;
935 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000936 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
937 unsigned ShAmt = SA->getValue();
938
939 // Compute the new bits that are at the top now.
940 uint64_t HighBits = (1ULL << ShAmt)-1;
941 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
942
943 if (I->getType()->isUnsigned()) { // Unsigned shift right.
944 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask << ShAmt,
945 KnownZero, KnownOne, Depth+1))
946 return true;
947 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
948 KnownZero >>= ShAmt;
949 KnownOne >>= ShAmt;
950 KnownZero |= HighBits; // high bits known zero.
951 } else { // Signed shift right.
952 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask << ShAmt,
953 KnownZero, KnownOne, Depth+1))
954 return true;
955 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
956 KnownZero >>= SA->getValue();
957 KnownOne >>= SA->getValue();
958
959 // Handle the sign bits.
960 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
961 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
962
963 // If the input sign bit is known to be zero, or if none of the top bits
964 // are demanded, turn this into an unsigned shift right.
965 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
966 // Convert the input to unsigned.
967 Instruction *NewVal;
968 NewVal = new CastInst(I->getOperand(0),
969 I->getType()->getUnsignedVersion(),
970 I->getOperand(0)->getName());
971 InsertNewInstBefore(NewVal, *I);
972 // Perform the unsigned shift right.
973 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
974 InsertNewInstBefore(NewVal, *I);
975 // Then cast that to the destination type.
976 NewVal = new CastInst(NewVal, I->getType(), I->getName());
977 InsertNewInstBefore(NewVal, *I);
978 return UpdateValueUsesWith(I, NewVal);
979 } else if (KnownOne & SignBit) { // New bits are known one.
980 KnownOne |= HighBits;
981 }
Chris Lattner2590e512006-02-07 06:56:34 +0000982 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000983 }
Chris Lattner2590e512006-02-07 06:56:34 +0000984 break;
985 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000986
987 // If the client is only demanding bits that we know, return the known
988 // constant.
989 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
990 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +0000991 return false;
992}
993
Chris Lattner623826c2004-09-28 21:48:02 +0000994// isTrueWhenEqual - Return true if the specified setcondinst instruction is
995// true when both operands are equal...
996//
997static bool isTrueWhenEqual(Instruction &I) {
998 return I.getOpcode() == Instruction::SetEQ ||
999 I.getOpcode() == Instruction::SetGE ||
1000 I.getOpcode() == Instruction::SetLE;
1001}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001002
1003/// AssociativeOpt - Perform an optimization on an associative operator. This
1004/// function is designed to check a chain of associative operators for a
1005/// potential to apply a certain optimization. Since the optimization may be
1006/// applicable if the expression was reassociated, this checks the chain, then
1007/// reassociates the expression as necessary to expose the optimization
1008/// opportunity. This makes use of a special Functor, which must define
1009/// 'shouldApply' and 'apply' methods.
1010///
1011template<typename Functor>
1012Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1013 unsigned Opcode = Root.getOpcode();
1014 Value *LHS = Root.getOperand(0);
1015
1016 // Quick check, see if the immediate LHS matches...
1017 if (F.shouldApply(LHS))
1018 return F.apply(Root);
1019
1020 // Otherwise, if the LHS is not of the same opcode as the root, return.
1021 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001022 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001023 // Should we apply this transform to the RHS?
1024 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1025
1026 // If not to the RHS, check to see if we should apply to the LHS...
1027 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1028 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1029 ShouldApply = true;
1030 }
1031
1032 // If the functor wants to apply the optimization to the RHS of LHSI,
1033 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1034 if (ShouldApply) {
1035 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001036
Chris Lattnerb8b97502003-08-13 19:01:45 +00001037 // Now all of the instructions are in the current basic block, go ahead
1038 // and perform the reassociation.
1039 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1040
1041 // First move the selected RHS to the LHS of the root...
1042 Root.setOperand(0, LHSI->getOperand(1));
1043
1044 // Make what used to be the LHS of the root be the user of the root...
1045 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001046 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001047 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1048 return 0;
1049 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001050 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001051 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001052 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1053 BasicBlock::iterator ARI = &Root; ++ARI;
1054 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1055 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001056
1057 // Now propagate the ExtraOperand down the chain of instructions until we
1058 // get to LHSI.
1059 while (TmpLHSI != LHSI) {
1060 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001061 // Move the instruction to immediately before the chain we are
1062 // constructing to avoid breaking dominance properties.
1063 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1064 BB->getInstList().insert(ARI, NextLHSI);
1065 ARI = NextLHSI;
1066
Chris Lattnerb8b97502003-08-13 19:01:45 +00001067 Value *NextOp = NextLHSI->getOperand(1);
1068 NextLHSI->setOperand(1, ExtraOperand);
1069 TmpLHSI = NextLHSI;
1070 ExtraOperand = NextOp;
1071 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001072
Chris Lattnerb8b97502003-08-13 19:01:45 +00001073 // Now that the instructions are reassociated, have the functor perform
1074 // the transformation...
1075 return F.apply(Root);
1076 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001077
Chris Lattnerb8b97502003-08-13 19:01:45 +00001078 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1079 }
1080 return 0;
1081}
1082
1083
1084// AddRHS - Implements: X + X --> X << 1
1085struct AddRHS {
1086 Value *RHS;
1087 AddRHS(Value *rhs) : RHS(rhs) {}
1088 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1089 Instruction *apply(BinaryOperator &Add) const {
1090 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1091 ConstantInt::get(Type::UByteTy, 1));
1092 }
1093};
1094
1095// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1096// iff C1&C2 == 0
1097struct AddMaskingAnd {
1098 Constant *C2;
1099 AddMaskingAnd(Constant *c) : C2(c) {}
1100 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001101 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001102 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001103 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001104 }
1105 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001106 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001107 }
1108};
1109
Chris Lattner86102b82005-01-01 16:22:27 +00001110static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001111 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001112 if (isa<CastInst>(I)) {
1113 if (Constant *SOC = dyn_cast<Constant>(SO))
1114 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001115
Chris Lattner86102b82005-01-01 16:22:27 +00001116 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1117 SO->getName() + ".cast"), I);
1118 }
1119
Chris Lattner183b3362004-04-09 19:05:30 +00001120 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001121 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1122 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001123
Chris Lattner183b3362004-04-09 19:05:30 +00001124 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1125 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001126 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1127 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001128 }
1129
1130 Value *Op0 = SO, *Op1 = ConstOperand;
1131 if (!ConstIsRHS)
1132 std::swap(Op0, Op1);
1133 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001134 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1135 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1136 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1137 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001138 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001139 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001140 abort();
1141 }
Chris Lattner86102b82005-01-01 16:22:27 +00001142 return IC->InsertNewInstBefore(New, I);
1143}
1144
1145// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1146// constant as the other operand, try to fold the binary operator into the
1147// select arguments. This also works for Cast instructions, which obviously do
1148// not have a second operand.
1149static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1150 InstCombiner *IC) {
1151 // Don't modify shared select instructions
1152 if (!SI->hasOneUse()) return 0;
1153 Value *TV = SI->getOperand(1);
1154 Value *FV = SI->getOperand(2);
1155
1156 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001157 // Bool selects with constant operands can be folded to logical ops.
1158 if (SI->getType() == Type::BoolTy) return 0;
1159
Chris Lattner86102b82005-01-01 16:22:27 +00001160 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1161 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1162
1163 return new SelectInst(SI->getCondition(), SelectTrueVal,
1164 SelectFalseVal);
1165 }
1166 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001167}
1168
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001169
1170/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1171/// node as operand #0, see if we can fold the instruction into the PHI (which
1172/// is only possible if all operands to the PHI are constants).
1173Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1174 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001175 unsigned NumPHIValues = PN->getNumIncomingValues();
1176 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1177 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001178
1179 // Check to see if all of the operands of the PHI are constants. If not, we
1180 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001181 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001182 if (!isa<Constant>(PN->getIncomingValue(i)))
1183 return 0;
1184
1185 // Okay, we can do the transformation: create the new PHI node.
1186 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1187 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001188 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001189 InsertNewInstBefore(NewPN, *PN);
1190
1191 // Next, add all of the operands to the PHI.
1192 if (I.getNumOperands() == 2) {
1193 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001194 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001195 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1196 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1197 PN->getIncomingBlock(i));
1198 }
1199 } else {
1200 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1201 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001202 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001203 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1204 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1205 PN->getIncomingBlock(i));
1206 }
1207 }
1208 return ReplaceInstUsesWith(I, NewPN);
1209}
1210
Chris Lattner113f4f42002-06-25 16:13:24 +00001211Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001212 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001213 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001214
Chris Lattnercf4a9962004-04-10 22:01:55 +00001215 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001216 // X + undef -> undef
1217 if (isa<UndefValue>(RHS))
1218 return ReplaceInstUsesWith(I, RHS);
1219
Chris Lattnercf4a9962004-04-10 22:01:55 +00001220 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001221 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1222 if (RHSC->isNullValue())
1223 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001224 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1225 if (CFP->isExactlyValue(-0.0))
1226 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001227 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001228
Chris Lattnercf4a9962004-04-10 22:01:55 +00001229 // X + (signbit) --> X ^ signbit
1230 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001231 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001232 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001233 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001234 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001235
1236 if (isa<PHINode>(LHS))
1237 if (Instruction *NV = FoldOpIntoPhi(I))
1238 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001239
Chris Lattner330628a2006-01-06 17:59:59 +00001240 ConstantInt *XorRHS = 0;
1241 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001242 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1243 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1244 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1245 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1246
1247 uint64_t C0080Val = 1ULL << 31;
1248 int64_t CFF80Val = -C0080Val;
1249 unsigned Size = 32;
1250 do {
1251 if (TySizeBits > Size) {
1252 bool Found = false;
1253 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1254 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1255 if (RHSSExt == CFF80Val) {
1256 if (XorRHS->getZExtValue() == C0080Val)
1257 Found = true;
1258 } else if (RHSZExt == C0080Val) {
1259 if (XorRHS->getSExtValue() == CFF80Val)
1260 Found = true;
1261 }
1262 if (Found) {
1263 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001264 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001265 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001266 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001267 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001268 Size = 0; // Not a sign ext, but can't be any others either.
1269 goto FoundSExt;
1270 }
1271 }
1272 Size >>= 1;
1273 C0080Val >>= Size;
1274 CFF80Val >>= Size;
1275 } while (Size >= 8);
1276
1277FoundSExt:
1278 const Type *MiddleType = 0;
1279 switch (Size) {
1280 default: break;
1281 case 32: MiddleType = Type::IntTy; break;
1282 case 16: MiddleType = Type::ShortTy; break;
1283 case 8: MiddleType = Type::SByteTy; break;
1284 }
1285 if (MiddleType) {
1286 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1287 InsertNewInstBefore(NewTrunc, I);
1288 return new CastInst(NewTrunc, I.getType());
1289 }
1290 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001291 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001292
Chris Lattnerb8b97502003-08-13 19:01:45 +00001293 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001294 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001295 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001296
1297 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1298 if (RHSI->getOpcode() == Instruction::Sub)
1299 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1300 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1301 }
1302 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1303 if (LHSI->getOpcode() == Instruction::Sub)
1304 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1305 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1306 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001307 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001308
Chris Lattner147e9752002-05-08 22:46:53 +00001309 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001310 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001311 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001312
1313 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001314 if (!isa<Constant>(RHS))
1315 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001316 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001317
Misha Brukmanb1c93172005-04-21 23:48:37 +00001318
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001319 ConstantInt *C2;
1320 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1321 if (X == RHS) // X*C + X --> X * (C+1)
1322 return BinaryOperator::createMul(RHS, AddOne(C2));
1323
1324 // X*C1 + X*C2 --> X * (C1+C2)
1325 ConstantInt *C1;
1326 if (X == dyn_castFoldableMul(RHS, C1))
1327 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001328 }
1329
1330 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001331 if (dyn_castFoldableMul(RHS, C2) == LHS)
1332 return BinaryOperator::createMul(LHS, AddOne(C2));
1333
Chris Lattner57c8d992003-02-18 19:57:07 +00001334
Chris Lattnerb8b97502003-08-13 19:01:45 +00001335 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001336 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001337 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001338
Chris Lattnerb9cde762003-10-02 15:11:26 +00001339 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001340 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001341 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1342 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1343 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001344 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001345
Chris Lattnerbff91d92004-10-08 05:07:56 +00001346 // (X & FF00) + xx00 -> (X+xx00) & FF00
1347 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1348 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1349 if (Anded == CRHS) {
1350 // See if all bits from the first bit set in the Add RHS up are included
1351 // in the mask. First, get the rightmost bit.
1352 uint64_t AddRHSV = CRHS->getRawValue();
1353
1354 // Form a mask of all bits from the lowest bit added through the top.
1355 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001356 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001357
1358 // See if the and mask includes all of these bits.
1359 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001360
Chris Lattnerbff91d92004-10-08 05:07:56 +00001361 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1362 // Okay, the xform is safe. Insert the new add pronto.
1363 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1364 LHS->getName()), I);
1365 return BinaryOperator::createAnd(NewAdd, C2);
1366 }
1367 }
1368 }
1369
Chris Lattnerd4252a72004-07-30 07:50:03 +00001370 // Try to fold constant add into select arguments.
1371 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001372 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001373 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001374 }
1375
Chris Lattner113f4f42002-06-25 16:13:24 +00001376 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001377}
1378
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001379// isSignBit - Return true if the value represented by the constant only has the
1380// highest order bit set.
1381static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001382 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001383 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001384}
1385
Chris Lattner022167f2004-03-13 00:11:49 +00001386/// RemoveNoopCast - Strip off nonconverting casts from the value.
1387///
1388static Value *RemoveNoopCast(Value *V) {
1389 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1390 const Type *CTy = CI->getType();
1391 const Type *OpTy = CI->getOperand(0)->getType();
1392 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001393 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001394 return RemoveNoopCast(CI->getOperand(0));
1395 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1396 return RemoveNoopCast(CI->getOperand(0));
1397 }
1398 return V;
1399}
1400
Chris Lattner113f4f42002-06-25 16:13:24 +00001401Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001402 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001403
Chris Lattnere6794492002-08-12 21:17:25 +00001404 if (Op0 == Op1) // sub X, X -> 0
1405 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001406
Chris Lattnere6794492002-08-12 21:17:25 +00001407 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001408 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001409 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001410
Chris Lattner81a7a232004-10-16 18:11:37 +00001411 if (isa<UndefValue>(Op0))
1412 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1413 if (isa<UndefValue>(Op1))
1414 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1415
Chris Lattner8f2f5982003-11-05 01:06:05 +00001416 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1417 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001418 if (C->isAllOnesValue())
1419 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001420
Chris Lattner8f2f5982003-11-05 01:06:05 +00001421 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001422 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001423 if (match(Op1, m_Not(m_Value(X))))
1424 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001425 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001426 // -((uint)X >> 31) -> ((int)X >> 31)
1427 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001428 if (C->isNullValue()) {
1429 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1430 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001431 if (SI->getOpcode() == Instruction::Shr)
1432 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1433 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001434 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001435 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001436 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001437 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001438 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001439 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001440 // Ok, the transformation is safe. Insert a cast of the incoming
1441 // value, then the new shift, then the new cast.
1442 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1443 SI->getOperand(0)->getName());
1444 Value *InV = InsertNewInstBefore(FirstCast, I);
1445 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1446 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001447 if (NewShift->getType() == I.getType())
1448 return NewShift;
1449 else {
1450 InV = InsertNewInstBefore(NewShift, I);
1451 return new CastInst(NewShift, I.getType());
1452 }
Chris Lattner92295c52004-03-12 23:53:13 +00001453 }
1454 }
Chris Lattner022167f2004-03-13 00:11:49 +00001455 }
Chris Lattner183b3362004-04-09 19:05:30 +00001456
1457 // Try to fold constant sub into select arguments.
1458 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001459 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001460 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001461
1462 if (isa<PHINode>(Op0))
1463 if (Instruction *NV = FoldOpIntoPhi(I))
1464 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001465 }
1466
Chris Lattnera9be4492005-04-07 16:15:25 +00001467 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1468 if (Op1I->getOpcode() == Instruction::Add &&
1469 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001470 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001471 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001472 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001473 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001474 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1475 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1476 // C1-(X+C2) --> (C1-C2)-X
1477 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1478 Op1I->getOperand(0));
1479 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001480 }
1481
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001482 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001483 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1484 // is not used by anyone else...
1485 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001486 if (Op1I->getOpcode() == Instruction::Sub &&
1487 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001488 // Swap the two operands of the subexpr...
1489 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1490 Op1I->setOperand(0, IIOp1);
1491 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001492
Chris Lattner3082c5a2003-02-18 19:28:33 +00001493 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001494 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001495 }
1496
1497 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1498 //
1499 if (Op1I->getOpcode() == Instruction::And &&
1500 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1501 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1502
Chris Lattner396dbfe2004-06-09 05:08:07 +00001503 Value *NewNot =
1504 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001505 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001506 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001507
Chris Lattner0aee4b72004-10-06 15:08:25 +00001508 // -(X sdiv C) -> (X sdiv -C)
1509 if (Op1I->getOpcode() == Instruction::Div)
1510 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001511 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001512 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001513 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001514 ConstantExpr::getNeg(DivRHS));
1515
Chris Lattner57c8d992003-02-18 19:57:07 +00001516 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001517 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001518 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001519 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001520 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001521 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001522 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001523 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001524 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001525
Chris Lattner47060462005-04-07 17:14:51 +00001526 if (!Op0->getType()->isFloatingPoint())
1527 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1528 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001529 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1530 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1531 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1532 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001533 } else if (Op0I->getOpcode() == Instruction::Sub) {
1534 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1535 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001536 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001537
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001538 ConstantInt *C1;
1539 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1540 if (X == Op1) { // X*C - X --> X * (C-1)
1541 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1542 return BinaryOperator::createMul(Op1, CP1);
1543 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001544
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001545 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1546 if (X == dyn_castFoldableMul(Op1, C2))
1547 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1548 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001549 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001550}
1551
Chris Lattnere79e8542004-02-23 06:38:22 +00001552/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1553/// really just returns true if the most significant (sign) bit is set.
1554static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1555 if (RHS->getType()->isSigned()) {
1556 // True if source is LHS < 0 or LHS <= -1
1557 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1558 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1559 } else {
1560 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1561 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1562 // the size of the integer type.
1563 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001564 return RHSC->getValue() ==
1565 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001566 if (Opcode == Instruction::SetGT)
1567 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001568 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001569 }
1570 return false;
1571}
1572
Chris Lattner113f4f42002-06-25 16:13:24 +00001573Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001574 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001575 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001576
Chris Lattner81a7a232004-10-16 18:11:37 +00001577 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1578 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1579
Chris Lattnere6794492002-08-12 21:17:25 +00001580 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001581 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1582 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001583
1584 // ((X << C1)*C2) == (X * (C2 << C1))
1585 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1586 if (SI->getOpcode() == Instruction::Shl)
1587 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001588 return BinaryOperator::createMul(SI->getOperand(0),
1589 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001590
Chris Lattnercce81be2003-09-11 22:24:54 +00001591 if (CI->isNullValue())
1592 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1593 if (CI->equalsInt(1)) // X * 1 == X
1594 return ReplaceInstUsesWith(I, Op0);
1595 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001596 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001597
Chris Lattnercce81be2003-09-11 22:24:54 +00001598 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001599 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1600 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001601 return new ShiftInst(Instruction::Shl, Op0,
1602 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001603 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001604 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001605 if (Op1F->isNullValue())
1606 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001607
Chris Lattner3082c5a2003-02-18 19:28:33 +00001608 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1609 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1610 if (Op1F->getValue() == 1.0)
1611 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1612 }
Chris Lattner183b3362004-04-09 19:05:30 +00001613
1614 // Try to fold constant mul into select arguments.
1615 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001616 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001617 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001618
1619 if (isa<PHINode>(Op0))
1620 if (Instruction *NV = FoldOpIntoPhi(I))
1621 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001622 }
1623
Chris Lattner934a64cf2003-03-10 23:23:04 +00001624 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1625 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001626 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001627
Chris Lattner2635b522004-02-23 05:39:21 +00001628 // If one of the operands of the multiply is a cast from a boolean value, then
1629 // we know the bool is either zero or one, so this is a 'masking' multiply.
1630 // See if we can simplify things based on how the boolean was originally
1631 // formed.
1632 CastInst *BoolCast = 0;
1633 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1634 if (CI->getOperand(0)->getType() == Type::BoolTy)
1635 BoolCast = CI;
1636 if (!BoolCast)
1637 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1638 if (CI->getOperand(0)->getType() == Type::BoolTy)
1639 BoolCast = CI;
1640 if (BoolCast) {
1641 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1642 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1643 const Type *SCOpTy = SCIOp0->getType();
1644
Chris Lattnere79e8542004-02-23 06:38:22 +00001645 // If the setcc is true iff the sign bit of X is set, then convert this
1646 // multiply into a shift/and combination.
1647 if (isa<ConstantInt>(SCIOp1) &&
1648 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001649 // Shift the X value right to turn it into "all signbits".
1650 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001651 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001652 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001653 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001654 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1655 SCIOp0->getName()), I);
1656 }
1657
1658 Value *V =
1659 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1660 BoolCast->getOperand(0)->getName()+
1661 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001662
1663 // If the multiply type is not the same as the source type, sign extend
1664 // or truncate to the multiply type.
1665 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001666 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001667
Chris Lattner2635b522004-02-23 05:39:21 +00001668 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001669 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001670 }
1671 }
1672 }
1673
Chris Lattner113f4f42002-06-25 16:13:24 +00001674 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001675}
1676
Chris Lattner113f4f42002-06-25 16:13:24 +00001677Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001678 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001679
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001680 if (isa<UndefValue>(Op0)) // undef / X -> 0
1681 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1682 if (isa<UndefValue>(Op1))
1683 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1684
1685 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001686 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001687 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001688 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001689
Chris Lattnere20c3342004-04-26 14:01:59 +00001690 // div X, -1 == -X
1691 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001692 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001693
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001694 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001695 if (LHS->getOpcode() == Instruction::Div)
1696 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001697 // (X / C1) / C2 -> X / (C1*C2)
1698 return BinaryOperator::createDiv(LHS->getOperand(0),
1699 ConstantExpr::getMul(RHS, LHSRHS));
1700 }
1701
Chris Lattner3082c5a2003-02-18 19:28:33 +00001702 // Check to see if this is an unsigned division with an exact power of 2,
1703 // if so, convert to a right shift.
1704 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1705 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001706 if (isPowerOf2_64(Val)) {
1707 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001708 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001709 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001710 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001711
Chris Lattner4ad08352004-10-09 02:50:40 +00001712 // -X/C -> X/-C
1713 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001714 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001715 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1716
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001717 if (!RHS->isNullValue()) {
1718 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001719 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001720 return R;
1721 if (isa<PHINode>(Op0))
1722 if (Instruction *NV = FoldOpIntoPhi(I))
1723 return NV;
1724 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001725 }
1726
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001727 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1728 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1729 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1730 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1731 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1732 if (STO->getValue() == 0) { // Couldn't be this argument.
1733 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001734 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001735 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001736 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001737 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001738 }
1739
Chris Lattner42362612005-04-08 04:03:26 +00001740 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001741 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1742 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001743 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1744 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1745 TC, SI->getName()+".t");
1746 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001747
Chris Lattner42362612005-04-08 04:03:26 +00001748 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1749 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1750 FC, SI->getName()+".f");
1751 FSI = InsertNewInstBefore(FSI, I);
1752 return new SelectInst(SI->getOperand(0), TSI, FSI);
1753 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001754 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001755
Chris Lattner3082c5a2003-02-18 19:28:33 +00001756 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001757 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001758 if (LHS->equalsInt(0))
1759 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1760
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001761 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001762 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001763 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001764 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1765 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001766 const Type *NTy = Op0->getType()->getUnsignedVersion();
1767 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1768 InsertNewInstBefore(LHS, I);
1769 Value *RHS;
1770 if (Constant *R = dyn_cast<Constant>(Op1))
1771 RHS = ConstantExpr::getCast(R, NTy);
1772 else
1773 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1774 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1775 InsertNewInstBefore(Div, I);
1776 return new CastInst(Div, I.getType());
1777 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001778 } else {
1779 // Known to be an unsigned division.
1780 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1781 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1782 if (RHSI->getOpcode() == Instruction::Shl &&
1783 isa<ConstantUInt>(RHSI->getOperand(0))) {
1784 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1785 if (isPowerOf2_64(C1)) {
1786 unsigned C2 = Log2_64(C1);
1787 Value *Add = RHSI->getOperand(1);
1788 if (C2) {
1789 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1790 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1791 "tmp"), I);
1792 }
1793 return new ShiftInst(Instruction::Shr, Op0, Add);
1794 }
1795 }
1796 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001797 }
1798
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001799 return 0;
1800}
1801
1802
Chris Lattner113f4f42002-06-25 16:13:24 +00001803Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001804 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001805 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001806 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001807 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001808 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001809 // X % -Y -> X % Y
1810 AddUsesToWorkList(I);
1811 I.setOperand(1, RHSNeg);
1812 return &I;
1813 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001814
1815 // If the top bits of both operands are zero (i.e. we can prove they are
1816 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001817 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1818 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001819 const Type *NTy = Op0->getType()->getUnsignedVersion();
1820 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1821 InsertNewInstBefore(LHS, I);
1822 Value *RHS;
1823 if (Constant *R = dyn_cast<Constant>(Op1))
1824 RHS = ConstantExpr::getCast(R, NTy);
1825 else
1826 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1827 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1828 InsertNewInstBefore(Rem, I);
1829 return new CastInst(Rem, I.getType());
1830 }
1831 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001832
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001833 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001834 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001835 if (isa<UndefValue>(Op1))
1836 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001837
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001838 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001839 if (RHS->equalsInt(1)) // X % 1 == 0
1840 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1841
1842 // Check to see if this is an unsigned remainder with an exact power of 2,
1843 // if so, convert to a bitwise and.
1844 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1845 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001846 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001847 return BinaryOperator::createAnd(Op0,
1848 ConstantUInt::get(I.getType(), Val-1));
1849
1850 if (!RHS->isNullValue()) {
1851 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001852 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001853 return R;
1854 if (isa<PHINode>(Op0))
1855 if (Instruction *NV = FoldOpIntoPhi(I))
1856 return NV;
1857 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001858 }
1859
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001860 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1861 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1862 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1863 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1864 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1865 if (STO->getValue() == 0) { // Couldn't be this argument.
1866 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001867 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001868 } else if (SFO->getValue() == 0) {
1869 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001870 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001871 }
1872
1873 if (!(STO->getValue() & (STO->getValue()-1)) &&
1874 !(SFO->getValue() & (SFO->getValue()-1))) {
1875 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1876 SubOne(STO), SI->getName()+".t"), I);
1877 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1878 SubOne(SFO), SI->getName()+".f"), I);
1879 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1880 }
1881 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001882
Chris Lattner3082c5a2003-02-18 19:28:33 +00001883 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001884 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001885 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001886 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1887
Chris Lattner2e90b732006-02-05 07:54:04 +00001888
1889 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1890 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1891 if (I.getType()->isUnsigned() &&
1892 RHSI->getOpcode() == Instruction::Shl &&
1893 isa<ConstantUInt>(RHSI->getOperand(0))) {
1894 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1895 if (isPowerOf2_64(C1)) {
1896 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1897 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1898 "tmp"), I);
1899 return BinaryOperator::createAnd(Op0, Add);
1900 }
1901 }
1902 }
1903
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001904 return 0;
1905}
1906
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001907// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001908static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001909 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1910 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001911
1912 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001913
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001914 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001915 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001916 int64_t Val = INT64_MAX; // All ones
1917 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1918 return CS->getValue() == Val-1;
1919}
1920
1921// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001922static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001923 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1924 return CU->getValue() == 1;
1925
1926 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001927
1928 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001929 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001930 int64_t Val = -1; // All ones
1931 Val <<= TypeBits-1; // Shift over to the right spot
1932 return CS->getValue() == Val+1;
1933}
1934
Chris Lattner35167c32004-06-09 07:59:58 +00001935// isOneBitSet - Return true if there is exactly one bit set in the specified
1936// constant.
1937static bool isOneBitSet(const ConstantInt *CI) {
1938 uint64_t V = CI->getRawValue();
1939 return V && (V & (V-1)) == 0;
1940}
1941
Chris Lattner8fc5af42004-09-23 21:46:38 +00001942#if 0 // Currently unused
1943// isLowOnes - Return true if the constant is of the form 0+1+.
1944static bool isLowOnes(const ConstantInt *CI) {
1945 uint64_t V = CI->getRawValue();
1946
1947 // There won't be bits set in parts that the type doesn't contain.
1948 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1949
1950 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1951 return U && V && (U & V) == 0;
1952}
1953#endif
1954
1955// isHighOnes - Return true if the constant is of the form 1+0+.
1956// This is the same as lowones(~X).
1957static bool isHighOnes(const ConstantInt *CI) {
1958 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001959 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001960
1961 // There won't be bits set in parts that the type doesn't contain.
1962 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1963
1964 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1965 return U && V && (U & V) == 0;
1966}
1967
1968
Chris Lattner3ac7c262003-08-13 20:16:26 +00001969/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1970/// are carefully arranged to allow folding of expressions such as:
1971///
1972/// (A < B) | (A > B) --> (A != B)
1973///
1974/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1975/// represents that the comparison is true if A == B, and bit value '1' is true
1976/// if A < B.
1977///
1978static unsigned getSetCondCode(const SetCondInst *SCI) {
1979 switch (SCI->getOpcode()) {
1980 // False -> 0
1981 case Instruction::SetGT: return 1;
1982 case Instruction::SetEQ: return 2;
1983 case Instruction::SetGE: return 3;
1984 case Instruction::SetLT: return 4;
1985 case Instruction::SetNE: return 5;
1986 case Instruction::SetLE: return 6;
1987 // True -> 7
1988 default:
1989 assert(0 && "Invalid SetCC opcode!");
1990 return 0;
1991 }
1992}
1993
1994/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1995/// opcode and two operands into either a constant true or false, or a brand new
1996/// SetCC instruction.
1997static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1998 switch (Opcode) {
1999 case 0: return ConstantBool::False;
2000 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2001 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2002 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2003 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2004 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2005 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2006 case 7: return ConstantBool::True;
2007 default: assert(0 && "Illegal SetCCCode!"); return 0;
2008 }
2009}
2010
2011// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2012struct FoldSetCCLogical {
2013 InstCombiner &IC;
2014 Value *LHS, *RHS;
2015 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2016 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2017 bool shouldApply(Value *V) const {
2018 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2019 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2020 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2021 return false;
2022 }
2023 Instruction *apply(BinaryOperator &Log) const {
2024 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2025 if (SCI->getOperand(0) != LHS) {
2026 assert(SCI->getOperand(1) == LHS);
2027 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2028 }
2029
2030 unsigned LHSCode = getSetCondCode(SCI);
2031 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2032 unsigned Code;
2033 switch (Log.getOpcode()) {
2034 case Instruction::And: Code = LHSCode & RHSCode; break;
2035 case Instruction::Or: Code = LHSCode | RHSCode; break;
2036 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002037 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002038 }
2039
2040 Value *RV = getSetCCValue(Code, LHS, RHS);
2041 if (Instruction *I = dyn_cast<Instruction>(RV))
2042 return I;
2043 // Otherwise, it's a constant boolean value...
2044 return IC.ReplaceInstUsesWith(Log, RV);
2045 }
2046};
2047
Chris Lattnerba1cb382003-09-19 17:17:26 +00002048// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2049// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2050// guaranteed to be either a shift instruction or a binary operator.
2051Instruction *InstCombiner::OptAndOp(Instruction *Op,
2052 ConstantIntegral *OpRHS,
2053 ConstantIntegral *AndRHS,
2054 BinaryOperator &TheAnd) {
2055 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002056 Constant *Together = 0;
2057 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002058 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002059
Chris Lattnerba1cb382003-09-19 17:17:26 +00002060 switch (Op->getOpcode()) {
2061 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002062 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002063 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2064 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002065 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002066 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002067 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002068 }
2069 break;
2070 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002071 if (Together == AndRHS) // (X | C) & C --> C
2072 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002073
Chris Lattner86102b82005-01-01 16:22:27 +00002074 if (Op->hasOneUse() && Together != OpRHS) {
2075 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2076 std::string Op0Name = Op->getName(); Op->setName("");
2077 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2078 InsertNewInstBefore(Or, TheAnd);
2079 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002080 }
2081 break;
2082 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002083 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002084 // Adding a one to a single bit bit-field should be turned into an XOR
2085 // of the bit. First thing to check is to see if this AND is with a
2086 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002087 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002088
2089 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002090 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002091
2092 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002093 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002094 // Ok, at this point, we know that we are masking the result of the
2095 // ADD down to exactly one bit. If the constant we are adding has
2096 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002097 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002098
Chris Lattnerba1cb382003-09-19 17:17:26 +00002099 // Check to see if any bits below the one bit set in AndRHSV are set.
2100 if ((AddRHS & (AndRHSV-1)) == 0) {
2101 // If not, the only thing that can effect the output of the AND is
2102 // the bit specified by AndRHSV. If that bit is set, the effect of
2103 // the XOR is to toggle the bit. If it is clear, then the ADD has
2104 // no effect.
2105 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2106 TheAnd.setOperand(0, X);
2107 return &TheAnd;
2108 } else {
2109 std::string Name = Op->getName(); Op->setName("");
2110 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002111 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002112 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002113 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002114 }
2115 }
2116 }
2117 }
2118 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002119
2120 case Instruction::Shl: {
2121 // We know that the AND will not produce any of the bits shifted in, so if
2122 // the anded constant includes them, clear them now!
2123 //
2124 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002125 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2126 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002127
Chris Lattner7e794272004-09-24 15:21:34 +00002128 if (CI == ShlMask) { // Masking out bits that the shift already masks
2129 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2130 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002131 TheAnd.setOperand(1, CI);
2132 return &TheAnd;
2133 }
2134 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002135 }
Chris Lattner2da29172003-09-19 19:05:02 +00002136 case Instruction::Shr:
2137 // We know that the AND will not produce any of the bits shifted in, so if
2138 // the anded constant includes them, clear them now! This only applies to
2139 // unsigned shifts, because a signed shr may bring in set bits!
2140 //
2141 if (AndRHS->getType()->isUnsigned()) {
2142 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002143 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2144 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2145
2146 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2147 return ReplaceInstUsesWith(TheAnd, Op);
2148 } else if (CI != AndRHS) {
2149 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002150 return &TheAnd;
2151 }
Chris Lattner7e794272004-09-24 15:21:34 +00002152 } else { // Signed shr.
2153 // See if this is shifting in some sign extension, then masking it out
2154 // with an and.
2155 if (Op->hasOneUse()) {
2156 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2157 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2158 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002159 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002160 // Make the argument unsigned.
2161 Value *ShVal = Op->getOperand(0);
2162 ShVal = InsertCastBefore(ShVal,
2163 ShVal->getType()->getUnsignedVersion(),
2164 TheAnd);
2165 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2166 OpRHS, Op->getName()),
2167 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002168 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2169 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2170 TheAnd.getName()),
2171 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002172 return new CastInst(ShVal, Op->getType());
2173 }
2174 }
Chris Lattner2da29172003-09-19 19:05:02 +00002175 }
2176 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002177 }
2178 return 0;
2179}
2180
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002181
Chris Lattner6862fbd2004-09-29 17:40:11 +00002182/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2183/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2184/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2185/// insert new instructions.
2186Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2187 bool Inside, Instruction &IB) {
2188 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2189 "Lo is not <= Hi in range emission code!");
2190 if (Inside) {
2191 if (Lo == Hi) // Trivially false.
2192 return new SetCondInst(Instruction::SetNE, V, V);
2193 if (cast<ConstantIntegral>(Lo)->isMinValue())
2194 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002195
Chris Lattner6862fbd2004-09-29 17:40:11 +00002196 Constant *AddCST = ConstantExpr::getNeg(Lo);
2197 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2198 InsertNewInstBefore(Add, IB);
2199 // Convert to unsigned for the comparison.
2200 const Type *UnsType = Add->getType()->getUnsignedVersion();
2201 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2202 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2203 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2204 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2205 }
2206
2207 if (Lo == Hi) // Trivially true.
2208 return new SetCondInst(Instruction::SetEQ, V, V);
2209
2210 Hi = SubOne(cast<ConstantInt>(Hi));
2211 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2212 return new SetCondInst(Instruction::SetGT, V, Hi);
2213
2214 // Emit X-Lo > Hi-Lo-1
2215 Constant *AddCST = ConstantExpr::getNeg(Lo);
2216 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2217 InsertNewInstBefore(Add, IB);
2218 // Convert to unsigned for the comparison.
2219 const Type *UnsType = Add->getType()->getUnsignedVersion();
2220 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2221 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2222 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2223 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2224}
2225
Chris Lattnerb4b25302005-09-18 07:22:02 +00002226// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2227// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2228// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2229// not, since all 1s are not contiguous.
2230static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2231 uint64_t V = Val->getRawValue();
2232 if (!isShiftedMask_64(V)) return false;
2233
2234 // look for the first zero bit after the run of ones
2235 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2236 // look for the first non-zero bit
2237 ME = 64-CountLeadingZeros_64(V);
2238 return true;
2239}
2240
2241
2242
2243/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2244/// where isSub determines whether the operator is a sub. If we can fold one of
2245/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002246///
2247/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2248/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2249/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2250///
2251/// return (A +/- B).
2252///
2253Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2254 ConstantIntegral *Mask, bool isSub,
2255 Instruction &I) {
2256 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2257 if (!LHSI || LHSI->getNumOperands() != 2 ||
2258 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2259
2260 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2261
2262 switch (LHSI->getOpcode()) {
2263 default: return 0;
2264 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002265 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2266 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2267 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2268 break;
2269
2270 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2271 // part, we don't need any explicit masks to take them out of A. If that
2272 // is all N is, ignore it.
2273 unsigned MB, ME;
2274 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002275 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2276 Mask >>= 64-MB+1;
2277 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002278 break;
2279 }
2280 }
Chris Lattneraf517572005-09-18 04:24:45 +00002281 return 0;
2282 case Instruction::Or:
2283 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002284 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2285 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2286 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002287 break;
2288 return 0;
2289 }
2290
2291 Instruction *New;
2292 if (isSub)
2293 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2294 else
2295 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2296 return InsertNewInstBefore(New, I);
2297}
2298
Chris Lattner113f4f42002-06-25 16:13:24 +00002299Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002300 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002301 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002302
Chris Lattner81a7a232004-10-16 18:11:37 +00002303 if (isa<UndefValue>(Op1)) // X & undef -> 0
2304 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2305
Chris Lattner86102b82005-01-01 16:22:27 +00002306 // and X, X = X
2307 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002308 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002309
Chris Lattner5b2edb12006-02-12 08:02:11 +00002310 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002311 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002312 uint64_t KnownZero, KnownOne;
2313 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2314 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002315 return &I;
2316
Chris Lattner86102b82005-01-01 16:22:27 +00002317 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002318 uint64_t AndRHSMask = AndRHS->getZExtValue();
2319 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002320 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002321
Chris Lattnerba1cb382003-09-19 17:17:26 +00002322 // Optimize a variety of ((val OP C1) & C2) combinations...
2323 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2324 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002325 Value *Op0LHS = Op0I->getOperand(0);
2326 Value *Op0RHS = Op0I->getOperand(1);
2327 switch (Op0I->getOpcode()) {
2328 case Instruction::Xor:
2329 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002330 // If the mask is only needed on one incoming arm, push it up.
2331 if (Op0I->hasOneUse()) {
2332 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2333 // Not masking anything out for the LHS, move to RHS.
2334 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2335 Op0RHS->getName()+".masked");
2336 InsertNewInstBefore(NewRHS, I);
2337 return BinaryOperator::create(
2338 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002339 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002340 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002341 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2342 // Not masking anything out for the RHS, move to LHS.
2343 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2344 Op0LHS->getName()+".masked");
2345 InsertNewInstBefore(NewLHS, I);
2346 return BinaryOperator::create(
2347 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2348 }
2349 }
2350
Chris Lattner86102b82005-01-01 16:22:27 +00002351 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002352 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002353 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2354 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2355 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2356 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2357 return BinaryOperator::createAnd(V, AndRHS);
2358 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2359 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002360 break;
2361
2362 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002363 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2364 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2365 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2366 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2367 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002368 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002369 }
2370
Chris Lattner16464b32003-07-23 19:25:52 +00002371 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002372 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002373 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002374 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2375 const Type *SrcTy = CI->getOperand(0)->getType();
2376
Chris Lattner2c14cf72005-08-07 07:03:10 +00002377 // If this is an integer truncation or change from signed-to-unsigned, and
2378 // if the source is an and/or with immediate, transform it. This
2379 // frequently occurs for bitfield accesses.
2380 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2381 if (SrcTy->getPrimitiveSizeInBits() >=
2382 I.getType()->getPrimitiveSizeInBits() &&
2383 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002384 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002385 if (CastOp->getOpcode() == Instruction::And) {
2386 // Change: and (cast (and X, C1) to T), C2
2387 // into : and (cast X to T), trunc(C1)&C2
2388 // This will folds the two ands together, which may allow other
2389 // simplifications.
2390 Instruction *NewCast =
2391 new CastInst(CastOp->getOperand(0), I.getType(),
2392 CastOp->getName()+".shrunk");
2393 NewCast = InsertNewInstBefore(NewCast, I);
2394
2395 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2396 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2397 return BinaryOperator::createAnd(NewCast, C3);
2398 } else if (CastOp->getOpcode() == Instruction::Or) {
2399 // Change: and (cast (or X, C1) to T), C2
2400 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2401 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2402 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2403 return ReplaceInstUsesWith(I, AndRHS);
2404 }
2405 }
Chris Lattner33217db2003-07-23 19:36:21 +00002406 }
Chris Lattner183b3362004-04-09 19:05:30 +00002407
2408 // Try to fold constant and into select arguments.
2409 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002410 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002411 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002412 if (isa<PHINode>(Op0))
2413 if (Instruction *NV = FoldOpIntoPhi(I))
2414 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002415 }
2416
Chris Lattnerbb74e222003-03-10 23:06:50 +00002417 Value *Op0NotVal = dyn_castNotVal(Op0);
2418 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002419
Chris Lattner023a4832004-06-18 06:07:51 +00002420 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2421 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2422
Misha Brukman9c003d82004-07-30 12:50:08 +00002423 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002424 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002425 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2426 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002427 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002428 return BinaryOperator::createNot(Or);
2429 }
2430
Chris Lattner623826c2004-09-28 21:48:02 +00002431 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2432 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002433 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2434 return R;
2435
Chris Lattner623826c2004-09-28 21:48:02 +00002436 Value *LHSVal, *RHSVal;
2437 ConstantInt *LHSCst, *RHSCst;
2438 Instruction::BinaryOps LHSCC, RHSCC;
2439 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2440 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2441 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2442 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002443 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002444 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2445 // Ensure that the larger constant is on the RHS.
2446 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2447 SetCondInst *LHS = cast<SetCondInst>(Op0);
2448 if (cast<ConstantBool>(Cmp)->getValue()) {
2449 std::swap(LHS, RHS);
2450 std::swap(LHSCst, RHSCst);
2451 std::swap(LHSCC, RHSCC);
2452 }
2453
2454 // At this point, we know we have have two setcc instructions
2455 // comparing a value against two constants and and'ing the result
2456 // together. Because of the above check, we know that we only have
2457 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2458 // FoldSetCCLogical check above), that the two constants are not
2459 // equal.
2460 assert(LHSCst != RHSCst && "Compares not folded above?");
2461
2462 switch (LHSCC) {
2463 default: assert(0 && "Unknown integer condition code!");
2464 case Instruction::SetEQ:
2465 switch (RHSCC) {
2466 default: assert(0 && "Unknown integer condition code!");
2467 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2468 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2469 return ReplaceInstUsesWith(I, ConstantBool::False);
2470 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2471 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2472 return ReplaceInstUsesWith(I, LHS);
2473 }
2474 case Instruction::SetNE:
2475 switch (RHSCC) {
2476 default: assert(0 && "Unknown integer condition code!");
2477 case Instruction::SetLT:
2478 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2479 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2480 break; // (X != 13 & X < 15) -> no change
2481 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2482 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2483 return ReplaceInstUsesWith(I, RHS);
2484 case Instruction::SetNE:
2485 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2486 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2487 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2488 LHSVal->getName()+".off");
2489 InsertNewInstBefore(Add, I);
2490 const Type *UnsType = Add->getType()->getUnsignedVersion();
2491 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2492 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2493 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2494 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2495 }
2496 break; // (X != 13 & X != 15) -> no change
2497 }
2498 break;
2499 case Instruction::SetLT:
2500 switch (RHSCC) {
2501 default: assert(0 && "Unknown integer condition code!");
2502 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2503 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2504 return ReplaceInstUsesWith(I, ConstantBool::False);
2505 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2506 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2507 return ReplaceInstUsesWith(I, LHS);
2508 }
2509 case Instruction::SetGT:
2510 switch (RHSCC) {
2511 default: assert(0 && "Unknown integer condition code!");
2512 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2513 return ReplaceInstUsesWith(I, LHS);
2514 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2515 return ReplaceInstUsesWith(I, RHS);
2516 case Instruction::SetNE:
2517 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2518 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2519 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002520 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2521 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002522 }
2523 }
2524 }
2525 }
2526
Chris Lattner113f4f42002-06-25 16:13:24 +00002527 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002528}
2529
Chris Lattner113f4f42002-06-25 16:13:24 +00002530Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002531 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002532 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002533
Chris Lattner81a7a232004-10-16 18:11:37 +00002534 if (isa<UndefValue>(Op1))
2535 return ReplaceInstUsesWith(I, // X | undef -> -1
2536 ConstantIntegral::getAllOnesValue(I.getType()));
2537
Chris Lattner5b2edb12006-02-12 08:02:11 +00002538 // or X, X = X
2539 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002540 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002541
Chris Lattner5b2edb12006-02-12 08:02:11 +00002542 // See if we can simplify any instructions used by the instruction whose sole
2543 // purpose is to compute bits we don't care about.
2544 uint64_t KnownZero, KnownOne;
2545 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2546 KnownZero, KnownOne))
2547 return &I;
2548
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002549 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002550 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002551 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002552 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2553 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002554 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2555 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002556 InsertNewInstBefore(Or, I);
2557 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2558 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002559
Chris Lattnerd4252a72004-07-30 07:50:03 +00002560 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2561 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2562 std::string Op0Name = Op0->getName(); Op0->setName("");
2563 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2564 InsertNewInstBefore(Or, I);
2565 return BinaryOperator::createXor(Or,
2566 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002567 }
Chris Lattner183b3362004-04-09 19:05:30 +00002568
2569 // Try to fold constant and into select arguments.
2570 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002571 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002572 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002573 if (isa<PHINode>(Op0))
2574 if (Instruction *NV = FoldOpIntoPhi(I))
2575 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002576 }
2577
Chris Lattner330628a2006-01-06 17:59:59 +00002578 Value *A = 0, *B = 0;
2579 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002580
2581 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2582 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2583 return ReplaceInstUsesWith(I, Op1);
2584 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2585 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2586 return ReplaceInstUsesWith(I, Op0);
2587
Chris Lattnerb62f5082005-05-09 04:58:36 +00002588 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2589 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002590 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002591 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2592 Op0->setName("");
2593 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2594 }
2595
2596 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2597 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002598 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002599 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2600 Op0->setName("");
2601 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2602 }
2603
Chris Lattner15212982005-09-18 03:42:07 +00002604 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002605 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002606 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2607
2608 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2609 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2610
2611
Chris Lattner01f56c62005-09-18 06:02:59 +00002612 // If we have: ((V + N) & C1) | (V & C2)
2613 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2614 // replace with V+N.
2615 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002616 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002617 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2618 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2619 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002620 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002621 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002622 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002623 return ReplaceInstUsesWith(I, A);
2624 }
2625 // Or commutes, try both ways.
2626 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2627 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2628 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002629 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002630 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002631 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002632 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002633 }
2634 }
2635 }
Chris Lattner812aab72003-08-12 19:11:07 +00002636
Chris Lattnerd4252a72004-07-30 07:50:03 +00002637 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2638 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002639 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002640 ConstantIntegral::getAllOnesValue(I.getType()));
2641 } else {
2642 A = 0;
2643 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002644 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002645 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2646 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002647 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002648 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002649
Misha Brukman9c003d82004-07-30 12:50:08 +00002650 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002651 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2652 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2653 I.getName()+".demorgan"), I);
2654 return BinaryOperator::createNot(And);
2655 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002656 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002657
Chris Lattner3ac7c262003-08-13 20:16:26 +00002658 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002659 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002660 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2661 return R;
2662
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002663 Value *LHSVal, *RHSVal;
2664 ConstantInt *LHSCst, *RHSCst;
2665 Instruction::BinaryOps LHSCC, RHSCC;
2666 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2667 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2668 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2669 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002670 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002671 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2672 // Ensure that the larger constant is on the RHS.
2673 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2674 SetCondInst *LHS = cast<SetCondInst>(Op0);
2675 if (cast<ConstantBool>(Cmp)->getValue()) {
2676 std::swap(LHS, RHS);
2677 std::swap(LHSCst, RHSCst);
2678 std::swap(LHSCC, RHSCC);
2679 }
2680
2681 // At this point, we know we have have two setcc instructions
2682 // comparing a value against two constants and or'ing the result
2683 // together. Because of the above check, we know that we only have
2684 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2685 // FoldSetCCLogical check above), that the two constants are not
2686 // equal.
2687 assert(LHSCst != RHSCst && "Compares not folded above?");
2688
2689 switch (LHSCC) {
2690 default: assert(0 && "Unknown integer condition code!");
2691 case Instruction::SetEQ:
2692 switch (RHSCC) {
2693 default: assert(0 && "Unknown integer condition code!");
2694 case Instruction::SetEQ:
2695 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2696 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2697 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2698 LHSVal->getName()+".off");
2699 InsertNewInstBefore(Add, I);
2700 const Type *UnsType = Add->getType()->getUnsignedVersion();
2701 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2702 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2703 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2704 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2705 }
2706 break; // (X == 13 | X == 15) -> no change
2707
Chris Lattner5c219462005-04-19 06:04:18 +00002708 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2709 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002710 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2711 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2712 return ReplaceInstUsesWith(I, RHS);
2713 }
2714 break;
2715 case Instruction::SetNE:
2716 switch (RHSCC) {
2717 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002718 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2719 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2720 return ReplaceInstUsesWith(I, LHS);
2721 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002722 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002723 return ReplaceInstUsesWith(I, ConstantBool::True);
2724 }
2725 break;
2726 case Instruction::SetLT:
2727 switch (RHSCC) {
2728 default: assert(0 && "Unknown integer condition code!");
2729 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2730 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002731 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2732 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002733 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2734 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2735 return ReplaceInstUsesWith(I, RHS);
2736 }
2737 break;
2738 case Instruction::SetGT:
2739 switch (RHSCC) {
2740 default: assert(0 && "Unknown integer condition code!");
2741 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2742 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2743 return ReplaceInstUsesWith(I, LHS);
2744 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2745 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2746 return ReplaceInstUsesWith(I, ConstantBool::True);
2747 }
2748 }
2749 }
2750 }
Chris Lattner15212982005-09-18 03:42:07 +00002751
Chris Lattner113f4f42002-06-25 16:13:24 +00002752 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002753}
2754
Chris Lattnerc2076352004-02-16 01:20:27 +00002755// XorSelf - Implements: X ^ X --> 0
2756struct XorSelf {
2757 Value *RHS;
2758 XorSelf(Value *rhs) : RHS(rhs) {}
2759 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2760 Instruction *apply(BinaryOperator &Xor) const {
2761 return &Xor;
2762 }
2763};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002764
2765
Chris Lattner113f4f42002-06-25 16:13:24 +00002766Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002767 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002768 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002769
Chris Lattner81a7a232004-10-16 18:11:37 +00002770 if (isa<UndefValue>(Op1))
2771 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2772
Chris Lattnerc2076352004-02-16 01:20:27 +00002773 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2774 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2775 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002776 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002777 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00002778
2779 // See if we can simplify any instructions used by the instruction whose sole
2780 // purpose is to compute bits we don't care about.
2781 uint64_t KnownZero, KnownOne;
2782 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2783 KnownZero, KnownOne))
2784 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002785
Chris Lattner97638592003-07-23 21:37:07 +00002786 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00002787 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002788 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002789 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002790 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002791 return new SetCondInst(SCI->getInverseCondition(),
2792 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002793
Chris Lattner8f2f5982003-11-05 01:06:05 +00002794 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002795 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2796 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002797 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2798 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002799 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002800 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002801 }
Chris Lattner023a4832004-06-18 06:07:51 +00002802
2803 // ~(~X & Y) --> (X | ~Y)
2804 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2805 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2806 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2807 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002808 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002809 Op0I->getOperand(1)->getName()+".not");
2810 InsertNewInstBefore(NotY, I);
2811 return BinaryOperator::createOr(Op0NotVal, NotY);
2812 }
2813 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002814
Chris Lattner97638592003-07-23 21:37:07 +00002815 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00002816 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00002817 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002818 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002819 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2820 return BinaryOperator::createSub(
2821 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002822 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002823 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002824 }
Chris Lattner97638592003-07-23 21:37:07 +00002825 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002826 }
Chris Lattner183b3362004-04-09 19:05:30 +00002827
2828 // Try to fold constant and into select arguments.
2829 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002830 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002831 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002832 if (isa<PHINode>(Op0))
2833 if (Instruction *NV = FoldOpIntoPhi(I))
2834 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002835 }
2836
Chris Lattnerbb74e222003-03-10 23:06:50 +00002837 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002838 if (X == Op1)
2839 return ReplaceInstUsesWith(I,
2840 ConstantIntegral::getAllOnesValue(I.getType()));
2841
Chris Lattnerbb74e222003-03-10 23:06:50 +00002842 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002843 if (X == Op0)
2844 return ReplaceInstUsesWith(I,
2845 ConstantIntegral::getAllOnesValue(I.getType()));
2846
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002847 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002848 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002849 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2850 cast<BinaryOperator>(Op1I)->swapOperands();
2851 I.swapOperands();
2852 std::swap(Op0, Op1);
2853 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2854 I.swapOperands();
2855 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002856 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002857 } else if (Op1I->getOpcode() == Instruction::Xor) {
2858 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2859 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2860 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2861 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2862 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002863
2864 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002865 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002866 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2867 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002868 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002869 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2870 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002871 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002872 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002873 } else if (Op0I->getOpcode() == Instruction::Xor) {
2874 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2875 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2876 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2877 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002878 }
2879
Chris Lattner3ac7c262003-08-13 20:16:26 +00002880 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2881 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2882 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2883 return R;
2884
Chris Lattner113f4f42002-06-25 16:13:24 +00002885 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002886}
2887
Chris Lattner6862fbd2004-09-29 17:40:11 +00002888/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2889/// overflowed for this type.
2890static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2891 ConstantInt *In2) {
2892 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2893 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2894}
2895
2896static bool isPositive(ConstantInt *C) {
2897 return cast<ConstantSInt>(C)->getValue() >= 0;
2898}
2899
2900/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2901/// overflowed for this type.
2902static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2903 ConstantInt *In2) {
2904 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2905
2906 if (In1->getType()->isUnsigned())
2907 return cast<ConstantUInt>(Result)->getValue() <
2908 cast<ConstantUInt>(In1)->getValue();
2909 if (isPositive(In1) != isPositive(In2))
2910 return false;
2911 if (isPositive(In1))
2912 return cast<ConstantSInt>(Result)->getValue() <
2913 cast<ConstantSInt>(In1)->getValue();
2914 return cast<ConstantSInt>(Result)->getValue() >
2915 cast<ConstantSInt>(In1)->getValue();
2916}
2917
Chris Lattner0798af32005-01-13 20:14:25 +00002918/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2919/// code necessary to compute the offset from the base pointer (without adding
2920/// in the base pointer). Return the result as a signed integer of intptr size.
2921static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2922 TargetData &TD = IC.getTargetData();
2923 gep_type_iterator GTI = gep_type_begin(GEP);
2924 const Type *UIntPtrTy = TD.getIntPtrType();
2925 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2926 Value *Result = Constant::getNullValue(SIntPtrTy);
2927
2928 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00002929 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00002930
Chris Lattner0798af32005-01-13 20:14:25 +00002931 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2932 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002933 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002934 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2935 SIntPtrTy);
2936 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2937 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002938 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002939 Scale = ConstantExpr::getMul(OpC, Scale);
2940 if (Constant *RC = dyn_cast<Constant>(Result))
2941 Result = ConstantExpr::getAdd(RC, Scale);
2942 else {
2943 // Emit an add instruction.
2944 Result = IC.InsertNewInstBefore(
2945 BinaryOperator::createAdd(Result, Scale,
2946 GEP->getName()+".offs"), I);
2947 }
2948 }
2949 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002950 // Convert to correct type.
2951 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2952 Op->getName()+".c"), I);
2953 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002954 // We'll let instcombine(mul) convert this to a shl if possible.
2955 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2956 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002957
2958 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002959 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002960 GEP->getName()+".offs"), I);
2961 }
2962 }
2963 return Result;
2964}
2965
2966/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2967/// else. At this point we know that the GEP is on the LHS of the comparison.
2968Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2969 Instruction::BinaryOps Cond,
2970 Instruction &I) {
2971 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002972
2973 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2974 if (isa<PointerType>(CI->getOperand(0)->getType()))
2975 RHS = CI->getOperand(0);
2976
Chris Lattner0798af32005-01-13 20:14:25 +00002977 Value *PtrBase = GEPLHS->getOperand(0);
2978 if (PtrBase == RHS) {
2979 // As an optimization, we don't actually have to compute the actual value of
2980 // OFFSET if this is a seteq or setne comparison, just return whether each
2981 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002982 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2983 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002984 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2985 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002986 bool EmitIt = true;
2987 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2988 if (isa<UndefValue>(C)) // undef index -> undef.
2989 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2990 if (C->isNullValue())
2991 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002992 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2993 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002994 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002995 return ReplaceInstUsesWith(I, // No comparison is needed here.
2996 ConstantBool::get(Cond == Instruction::SetNE));
2997 }
2998
2999 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003000 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003001 new SetCondInst(Cond, GEPLHS->getOperand(i),
3002 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3003 if (InVal == 0)
3004 InVal = Comp;
3005 else {
3006 InVal = InsertNewInstBefore(InVal, I);
3007 InsertNewInstBefore(Comp, I);
3008 if (Cond == Instruction::SetNE) // True if any are unequal
3009 InVal = BinaryOperator::createOr(InVal, Comp);
3010 else // True if all are equal
3011 InVal = BinaryOperator::createAnd(InVal, Comp);
3012 }
3013 }
3014 }
3015
3016 if (InVal)
3017 return InVal;
3018 else
3019 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3020 ConstantBool::get(Cond == Instruction::SetEQ));
3021 }
Chris Lattner0798af32005-01-13 20:14:25 +00003022
3023 // Only lower this if the setcc is the only user of the GEP or if we expect
3024 // the result to fold to a constant!
3025 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3026 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3027 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3028 return new SetCondInst(Cond, Offset,
3029 Constant::getNullValue(Offset->getType()));
3030 }
3031 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003032 // If the base pointers are different, but the indices are the same, just
3033 // compare the base pointer.
3034 if (PtrBase != GEPRHS->getOperand(0)) {
3035 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003036 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003037 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003038 if (IndicesTheSame)
3039 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3040 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3041 IndicesTheSame = false;
3042 break;
3043 }
3044
3045 // If all indices are the same, just compare the base pointers.
3046 if (IndicesTheSame)
3047 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3048 GEPRHS->getOperand(0));
3049
3050 // Otherwise, the base pointers are different and the indices are
3051 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003052 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003053 }
Chris Lattner0798af32005-01-13 20:14:25 +00003054
Chris Lattner81e84172005-01-13 22:25:21 +00003055 // If one of the GEPs has all zero indices, recurse.
3056 bool AllZeros = true;
3057 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3058 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3059 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3060 AllZeros = false;
3061 break;
3062 }
3063 if (AllZeros)
3064 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3065 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003066
3067 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003068 AllZeros = true;
3069 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3070 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3071 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3072 AllZeros = false;
3073 break;
3074 }
3075 if (AllZeros)
3076 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3077
Chris Lattner4fa89822005-01-14 00:20:05 +00003078 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3079 // If the GEPs only differ by one index, compare it.
3080 unsigned NumDifferences = 0; // Keep track of # differences.
3081 unsigned DiffOperand = 0; // The operand that differs.
3082 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3083 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003084 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3085 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003086 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003087 NumDifferences = 2;
3088 break;
3089 } else {
3090 if (NumDifferences++) break;
3091 DiffOperand = i;
3092 }
3093 }
3094
3095 if (NumDifferences == 0) // SAME GEP?
3096 return ReplaceInstUsesWith(I, // No comparison is needed here.
3097 ConstantBool::get(Cond == Instruction::SetEQ));
3098 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003099 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3100 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003101
3102 // Convert the operands to signed values to make sure to perform a
3103 // signed comparison.
3104 const Type *NewTy = LHSV->getType()->getSignedVersion();
3105 if (LHSV->getType() != NewTy)
3106 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3107 LHSV->getName()), I);
3108 if (RHSV->getType() != NewTy)
3109 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3110 RHSV->getName()), I);
3111 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003112 }
3113 }
3114
Chris Lattner0798af32005-01-13 20:14:25 +00003115 // Only lower this if the setcc is the only user of the GEP or if we expect
3116 // the result to fold to a constant!
3117 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3118 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3119 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3120 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3121 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3122 return new SetCondInst(Cond, L, R);
3123 }
3124 }
3125 return 0;
3126}
3127
3128
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003129Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003130 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003131 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3132 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003133
3134 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003135 if (Op0 == Op1)
3136 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003137
Chris Lattner81a7a232004-10-16 18:11:37 +00003138 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3139 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3140
Chris Lattner15ff1e12004-11-14 07:33:16 +00003141 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3142 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003143 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3144 isa<ConstantPointerNull>(Op0)) &&
3145 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003146 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003147 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3148
3149 // setcc's with boolean values can always be turned into bitwise operations
3150 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003151 switch (I.getOpcode()) {
3152 default: assert(0 && "Invalid setcc instruction!");
3153 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003154 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003155 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003156 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003157 }
Chris Lattner4456da62004-08-11 00:50:51 +00003158 case Instruction::SetNE:
3159 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003160
Chris Lattner4456da62004-08-11 00:50:51 +00003161 case Instruction::SetGT:
3162 std::swap(Op0, Op1); // Change setgt -> setlt
3163 // FALL THROUGH
3164 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3165 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3166 InsertNewInstBefore(Not, I);
3167 return BinaryOperator::createAnd(Not, Op1);
3168 }
3169 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003170 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003171 // FALL THROUGH
3172 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3173 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3174 InsertNewInstBefore(Not, I);
3175 return BinaryOperator::createOr(Not, Op1);
3176 }
3177 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003178 }
3179
Chris Lattner2dd01742004-06-09 04:24:29 +00003180 // See if we are doing a comparison between a constant and an instruction that
3181 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003182 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003183 // Check to see if we are comparing against the minimum or maximum value...
3184 if (CI->isMinValue()) {
3185 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3186 return ReplaceInstUsesWith(I, ConstantBool::False);
3187 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3188 return ReplaceInstUsesWith(I, ConstantBool::True);
3189 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3190 return BinaryOperator::createSetEQ(Op0, Op1);
3191 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3192 return BinaryOperator::createSetNE(Op0, Op1);
3193
3194 } else if (CI->isMaxValue()) {
3195 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3196 return ReplaceInstUsesWith(I, ConstantBool::False);
3197 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3198 return ReplaceInstUsesWith(I, ConstantBool::True);
3199 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3200 return BinaryOperator::createSetEQ(Op0, Op1);
3201 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3202 return BinaryOperator::createSetNE(Op0, Op1);
3203
3204 // Comparing against a value really close to min or max?
3205 } else if (isMinValuePlusOne(CI)) {
3206 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3207 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3208 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3209 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3210
3211 } else if (isMaxValueMinusOne(CI)) {
3212 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3213 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3214 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3215 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3216 }
3217
3218 // If we still have a setle or setge instruction, turn it into the
3219 // appropriate setlt or setgt instruction. Since the border cases have
3220 // already been handled above, this requires little checking.
3221 //
3222 if (I.getOpcode() == Instruction::SetLE)
3223 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3224 if (I.getOpcode() == Instruction::SetGE)
3225 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3226
Chris Lattneree0f2802006-02-12 02:07:56 +00003227
3228 // See if we can fold the comparison based on bits known to be zero or one
3229 // in the input.
3230 uint64_t KnownZero, KnownOne;
3231 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3232 KnownZero, KnownOne, 0))
3233 return &I;
3234
3235 // Given the known and unknown bits, compute a range that the LHS could be
3236 // in.
3237 if (KnownOne | KnownZero) {
3238 if (Ty->isUnsigned()) { // Unsigned comparison.
3239 uint64_t Min, Max;
3240 uint64_t RHSVal = CI->getZExtValue();
3241 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3242 Min, Max);
3243 switch (I.getOpcode()) { // LE/GE have been folded already.
3244 default: assert(0 && "Unknown setcc opcode!");
3245 case Instruction::SetEQ:
3246 if (Max < RHSVal || Min > RHSVal)
3247 return ReplaceInstUsesWith(I, ConstantBool::False);
3248 break;
3249 case Instruction::SetNE:
3250 if (Max < RHSVal || Min > RHSVal)
3251 return ReplaceInstUsesWith(I, ConstantBool::True);
3252 break;
3253 case Instruction::SetLT:
3254 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3255 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3256 break;
3257 case Instruction::SetGT:
3258 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3259 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3260 break;
3261 }
3262 } else { // Signed comparison.
3263 int64_t Min, Max;
3264 int64_t RHSVal = CI->getSExtValue();
3265 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3266 Min, Max);
3267 switch (I.getOpcode()) { // LE/GE have been folded already.
3268 default: assert(0 && "Unknown setcc opcode!");
3269 case Instruction::SetEQ:
3270 if (Max < RHSVal || Min > RHSVal)
3271 return ReplaceInstUsesWith(I, ConstantBool::False);
3272 break;
3273 case Instruction::SetNE:
3274 if (Max < RHSVal || Min > RHSVal)
3275 return ReplaceInstUsesWith(I, ConstantBool::True);
3276 break;
3277 case Instruction::SetLT:
3278 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3279 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3280 break;
3281 case Instruction::SetGT:
3282 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3283 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3284 break;
3285 }
3286 }
3287 }
3288
3289
Chris Lattnere1e10e12004-05-25 06:32:08 +00003290 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003291 switch (LHSI->getOpcode()) {
3292 case Instruction::And:
3293 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3294 LHSI->getOperand(0)->hasOneUse()) {
3295 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3296 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3297 // happens a LOT in code produced by the C front-end, for bitfield
3298 // access.
3299 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003300 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3301
3302 // Check to see if there is a noop-cast between the shift and the and.
3303 if (!Shift) {
3304 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3305 if (CI->getOperand(0)->getType()->isIntegral() &&
3306 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3307 CI->getType()->getPrimitiveSizeInBits())
3308 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3309 }
3310
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003311 ConstantUInt *ShAmt;
3312 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003313 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3314 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003315
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003316 // We can fold this as long as we can't shift unknown bits
3317 // into the mask. This can only happen with signed shift
3318 // rights, as they sign-extend.
3319 if (ShAmt) {
3320 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003321 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003322 if (!CanFold) {
3323 // To test for the bad case of the signed shr, see if any
3324 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003325 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3326 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3327
3328 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003329 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003330 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3331 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003332 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3333 CanFold = true;
3334 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003335
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003336 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003337 Constant *NewCst;
3338 if (Shift->getOpcode() == Instruction::Shl)
3339 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3340 else
3341 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003342
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003343 // Check to see if we are shifting out any of the bits being
3344 // compared.
3345 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3346 // If we shifted bits out, the fold is not going to work out.
3347 // As a special case, check to see if this means that the
3348 // result is always true or false now.
3349 if (I.getOpcode() == Instruction::SetEQ)
3350 return ReplaceInstUsesWith(I, ConstantBool::False);
3351 if (I.getOpcode() == Instruction::SetNE)
3352 return ReplaceInstUsesWith(I, ConstantBool::True);
3353 } else {
3354 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003355 Constant *NewAndCST;
3356 if (Shift->getOpcode() == Instruction::Shl)
3357 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3358 else
3359 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3360 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003361 if (AndTy == Ty)
3362 LHSI->setOperand(0, Shift->getOperand(0));
3363 else {
3364 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3365 *Shift);
3366 LHSI->setOperand(0, NewCast);
3367 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003368 WorkList.push_back(Shift); // Shift is dead.
3369 AddUsesToWorkList(I);
3370 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003371 }
3372 }
Chris Lattner35167c32004-06-09 07:59:58 +00003373 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003374 }
3375 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003376
Chris Lattner272d5ca2004-09-28 18:22:15 +00003377 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3378 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3379 switch (I.getOpcode()) {
3380 default: break;
3381 case Instruction::SetEQ:
3382 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003383 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3384
3385 // Check that the shift amount is in range. If not, don't perform
3386 // undefined shifts. When the shift is visited it will be
3387 // simplified.
3388 if (ShAmt->getValue() >= TypeBits)
3389 break;
3390
Chris Lattner272d5ca2004-09-28 18:22:15 +00003391 // If we are comparing against bits always shifted out, the
3392 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003393 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003394 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3395 if (Comp != CI) {// Comparing against a bit that we know is zero.
3396 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3397 Constant *Cst = ConstantBool::get(IsSetNE);
3398 return ReplaceInstUsesWith(I, Cst);
3399 }
3400
3401 if (LHSI->hasOneUse()) {
3402 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003403 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003404 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3405
3406 Constant *Mask;
3407 if (CI->getType()->isUnsigned()) {
3408 Mask = ConstantUInt::get(CI->getType(), Val);
3409 } else if (ShAmtVal != 0) {
3410 Mask = ConstantSInt::get(CI->getType(), Val);
3411 } else {
3412 Mask = ConstantInt::getAllOnesValue(CI->getType());
3413 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003414
Chris Lattner272d5ca2004-09-28 18:22:15 +00003415 Instruction *AndI =
3416 BinaryOperator::createAnd(LHSI->getOperand(0),
3417 Mask, LHSI->getName()+".mask");
3418 Value *And = InsertNewInstBefore(AndI, I);
3419 return new SetCondInst(I.getOpcode(), And,
3420 ConstantExpr::getUShr(CI, ShAmt));
3421 }
3422 }
3423 }
3424 }
3425 break;
3426
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003427 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003428 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003429 switch (I.getOpcode()) {
3430 default: break;
3431 case Instruction::SetEQ:
3432 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003433
3434 // Check that the shift amount is in range. If not, don't perform
3435 // undefined shifts. When the shift is visited it will be
3436 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003437 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003438 if (ShAmt->getValue() >= TypeBits)
3439 break;
3440
Chris Lattner1023b872004-09-27 16:18:50 +00003441 // If we are comparing against bits always shifted out, the
3442 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003443 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003444 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003445
Chris Lattner1023b872004-09-27 16:18:50 +00003446 if (Comp != CI) {// Comparing against a bit that we know is zero.
3447 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3448 Constant *Cst = ConstantBool::get(IsSetNE);
3449 return ReplaceInstUsesWith(I, Cst);
3450 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003451
Chris Lattner1023b872004-09-27 16:18:50 +00003452 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003453 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003454
Chris Lattner1023b872004-09-27 16:18:50 +00003455 // Otherwise strength reduce the shift into an and.
3456 uint64_t Val = ~0ULL; // All ones.
3457 Val <<= ShAmtVal; // Shift over to the right spot.
3458
3459 Constant *Mask;
3460 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003461 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003462 Mask = ConstantUInt::get(CI->getType(), Val);
3463 } else {
3464 Mask = ConstantSInt::get(CI->getType(), Val);
3465 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003466
Chris Lattner1023b872004-09-27 16:18:50 +00003467 Instruction *AndI =
3468 BinaryOperator::createAnd(LHSI->getOperand(0),
3469 Mask, LHSI->getName()+".mask");
3470 Value *And = InsertNewInstBefore(AndI, I);
3471 return new SetCondInst(I.getOpcode(), And,
3472 ConstantExpr::getShl(CI, ShAmt));
3473 }
3474 break;
3475 }
3476 }
3477 }
3478 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003479
Chris Lattner6862fbd2004-09-29 17:40:11 +00003480 case Instruction::Div:
3481 // Fold: (div X, C1) op C2 -> range check
3482 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3483 // Fold this div into the comparison, producing a range check.
3484 // Determine, based on the divide type, what the range is being
3485 // checked. If there is an overflow on the low or high side, remember
3486 // it, otherwise compute the range [low, hi) bounding the new value.
3487 bool LoOverflow = false, HiOverflow = 0;
3488 ConstantInt *LoBound = 0, *HiBound = 0;
3489
3490 ConstantInt *Prod;
3491 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3492
Chris Lattnera92af962004-10-11 19:40:04 +00003493 Instruction::BinaryOps Opcode = I.getOpcode();
3494
Chris Lattner6862fbd2004-09-29 17:40:11 +00003495 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3496 } else if (LHSI->getType()->isUnsigned()) { // udiv
3497 LoBound = Prod;
3498 LoOverflow = ProdOV;
3499 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3500 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3501 if (CI->isNullValue()) { // (X / pos) op 0
3502 // Can't overflow.
3503 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3504 HiBound = DivRHS;
3505 } else if (isPositive(CI)) { // (X / pos) op pos
3506 LoBound = Prod;
3507 LoOverflow = ProdOV;
3508 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3509 } else { // (X / pos) op neg
3510 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3511 LoOverflow = AddWithOverflow(LoBound, Prod,
3512 cast<ConstantInt>(DivRHSH));
3513 HiBound = Prod;
3514 HiOverflow = ProdOV;
3515 }
3516 } else { // Divisor is < 0.
3517 if (CI->isNullValue()) { // (X / neg) op 0
3518 LoBound = AddOne(DivRHS);
3519 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003520 if (HiBound == DivRHS)
3521 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003522 } else if (isPositive(CI)) { // (X / neg) op pos
3523 HiOverflow = LoOverflow = ProdOV;
3524 if (!LoOverflow)
3525 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3526 HiBound = AddOne(Prod);
3527 } else { // (X / neg) op neg
3528 LoBound = Prod;
3529 LoOverflow = HiOverflow = ProdOV;
3530 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3531 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003532
Chris Lattnera92af962004-10-11 19:40:04 +00003533 // Dividing by a negate swaps the condition.
3534 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003535 }
3536
3537 if (LoBound) {
3538 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003539 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003540 default: assert(0 && "Unhandled setcc opcode!");
3541 case Instruction::SetEQ:
3542 if (LoOverflow && HiOverflow)
3543 return ReplaceInstUsesWith(I, ConstantBool::False);
3544 else if (HiOverflow)
3545 return new SetCondInst(Instruction::SetGE, X, LoBound);
3546 else if (LoOverflow)
3547 return new SetCondInst(Instruction::SetLT, X, HiBound);
3548 else
3549 return InsertRangeTest(X, LoBound, HiBound, true, I);
3550 case Instruction::SetNE:
3551 if (LoOverflow && HiOverflow)
3552 return ReplaceInstUsesWith(I, ConstantBool::True);
3553 else if (HiOverflow)
3554 return new SetCondInst(Instruction::SetLT, X, LoBound);
3555 else if (LoOverflow)
3556 return new SetCondInst(Instruction::SetGE, X, HiBound);
3557 else
3558 return InsertRangeTest(X, LoBound, HiBound, false, I);
3559 case Instruction::SetLT:
3560 if (LoOverflow)
3561 return ReplaceInstUsesWith(I, ConstantBool::False);
3562 return new SetCondInst(Instruction::SetLT, X, LoBound);
3563 case Instruction::SetGT:
3564 if (HiOverflow)
3565 return ReplaceInstUsesWith(I, ConstantBool::False);
3566 return new SetCondInst(Instruction::SetGE, X, HiBound);
3567 }
3568 }
3569 }
3570 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003571 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003572
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003573 // Simplify seteq and setne instructions...
3574 if (I.getOpcode() == Instruction::SetEQ ||
3575 I.getOpcode() == Instruction::SetNE) {
3576 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3577
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003578 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003579 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003580 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3581 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003582 case Instruction::Rem:
3583 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3584 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3585 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003586 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3587 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3588 if (isPowerOf2_64(V)) {
3589 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003590 const Type *UTy = BO->getType()->getUnsignedVersion();
3591 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3592 UTy, "tmp"), I);
3593 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3594 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3595 RHSCst, BO->getName()), I);
3596 return BinaryOperator::create(I.getOpcode(), NewRem,
3597 Constant::getNullValue(UTy));
3598 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003599 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003600 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003601
Chris Lattnerc992add2003-08-13 05:33:12 +00003602 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003603 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3604 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003605 if (BO->hasOneUse())
3606 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3607 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003608 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003609 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3610 // efficiently invertible, or if the add has just this one use.
3611 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003612
Chris Lattnerc992add2003-08-13 05:33:12 +00003613 if (Value *NegVal = dyn_castNegVal(BOp1))
3614 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3615 else if (Value *NegVal = dyn_castNegVal(BOp0))
3616 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003617 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003618 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3619 BO->setName("");
3620 InsertNewInstBefore(Neg, I);
3621 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3622 }
3623 }
3624 break;
3625 case Instruction::Xor:
3626 // For the xor case, we can xor two constants together, eliminating
3627 // the explicit xor.
3628 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3629 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003630 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003631
3632 // FALLTHROUGH
3633 case Instruction::Sub:
3634 // Replace (([sub|xor] A, B) != 0) with (A != B)
3635 if (CI->isNullValue())
3636 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3637 BO->getOperand(1));
3638 break;
3639
3640 case Instruction::Or:
3641 // If bits are being or'd in that are not present in the constant we
3642 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003643 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003644 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003645 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003646 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003647 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003648 break;
3649
3650 case Instruction::And:
3651 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003652 // If bits are being compared against that are and'd out, then the
3653 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003654 if (!ConstantExpr::getAnd(CI,
3655 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003656 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003657
Chris Lattner35167c32004-06-09 07:59:58 +00003658 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003659 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003660 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3661 Instruction::SetNE, Op0,
3662 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003663
Chris Lattnerc992add2003-08-13 05:33:12 +00003664 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3665 // to be a signed value as appropriate.
3666 if (isSignBit(BOC)) {
3667 Value *X = BO->getOperand(0);
3668 // If 'X' is not signed, insert a cast now...
3669 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003670 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003671 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003672 }
3673 return new SetCondInst(isSetNE ? Instruction::SetLT :
3674 Instruction::SetGE, X,
3675 Constant::getNullValue(X->getType()));
3676 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003677
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003678 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003679 if (CI->isNullValue() && isHighOnes(BOC)) {
3680 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003681 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003682
3683 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003684 if (NegX->getType()->isSigned()) {
3685 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3686 X = InsertCastBefore(X, DestTy, I);
3687 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003688 }
3689
3690 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003691 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003692 }
3693
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003694 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003695 default: break;
3696 }
3697 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003698 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003699 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003700 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3701 Value *CastOp = Cast->getOperand(0);
3702 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003703 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003704 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003705 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003706 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003707 "Source and destination signednesses should differ!");
3708 if (Cast->getType()->isSigned()) {
3709 // If this is a signed comparison, check for comparisons in the
3710 // vicinity of zero.
3711 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3712 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003713 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003714 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003715 else if (I.getOpcode() == Instruction::SetGT &&
3716 cast<ConstantSInt>(CI)->getValue() == -1)
3717 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003718 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003719 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003720 } else {
3721 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3722 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003723 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003724 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003725 return BinaryOperator::createSetGT(CastOp,
3726 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003727 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003728 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003729 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003730 return BinaryOperator::createSetLT(CastOp,
3731 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003732 }
3733 }
3734 }
Chris Lattnere967b342003-06-04 05:10:11 +00003735 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003736 }
3737
Chris Lattner77c32c32005-04-23 15:31:55 +00003738 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3739 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3740 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3741 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003742 case Instruction::GetElementPtr:
3743 if (RHSC->isNullValue()) {
3744 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3745 bool isAllZeros = true;
3746 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3747 if (!isa<Constant>(LHSI->getOperand(i)) ||
3748 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3749 isAllZeros = false;
3750 break;
3751 }
3752 if (isAllZeros)
3753 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3754 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3755 }
3756 break;
3757
Chris Lattner77c32c32005-04-23 15:31:55 +00003758 case Instruction::PHI:
3759 if (Instruction *NV = FoldOpIntoPhi(I))
3760 return NV;
3761 break;
3762 case Instruction::Select:
3763 // If either operand of the select is a constant, we can fold the
3764 // comparison into the select arms, which will cause one to be
3765 // constant folded and the select turned into a bitwise or.
3766 Value *Op1 = 0, *Op2 = 0;
3767 if (LHSI->hasOneUse()) {
3768 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3769 // Fold the known value into the constant operand.
3770 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3771 // Insert a new SetCC of the other select operand.
3772 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3773 LHSI->getOperand(2), RHSC,
3774 I.getName()), I);
3775 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3776 // Fold the known value into the constant operand.
3777 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3778 // Insert a new SetCC of the other select operand.
3779 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3780 LHSI->getOperand(1), RHSC,
3781 I.getName()), I);
3782 }
3783 }
Jeff Cohen82639852005-04-23 21:38:35 +00003784
Chris Lattner77c32c32005-04-23 15:31:55 +00003785 if (Op1)
3786 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3787 break;
3788 }
3789 }
3790
Chris Lattner0798af32005-01-13 20:14:25 +00003791 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3792 if (User *GEP = dyn_castGetElementPtr(Op0))
3793 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3794 return NI;
3795 if (User *GEP = dyn_castGetElementPtr(Op1))
3796 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3797 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3798 return NI;
3799
Chris Lattner16930792003-11-03 04:25:02 +00003800 // Test to see if the operands of the setcc are casted versions of other
3801 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003802 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3803 Value *CastOp0 = CI->getOperand(0);
3804 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003805 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003806 (I.getOpcode() == Instruction::SetEQ ||
3807 I.getOpcode() == Instruction::SetNE)) {
3808 // We keep moving the cast from the left operand over to the right
3809 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003810 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003811
Chris Lattner16930792003-11-03 04:25:02 +00003812 // If operand #1 is a cast instruction, see if we can eliminate it as
3813 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003814 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3815 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003816 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003817 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003818
Chris Lattner16930792003-11-03 04:25:02 +00003819 // If Op1 is a constant, we can fold the cast into the constant.
3820 if (Op1->getType() != Op0->getType())
3821 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3822 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3823 } else {
3824 // Otherwise, cast the RHS right before the setcc
3825 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3826 InsertNewInstBefore(cast<Instruction>(Op1), I);
3827 }
3828 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3829 }
3830
Chris Lattner6444c372003-11-03 05:17:03 +00003831 // Handle the special case of: setcc (cast bool to X), <cst>
3832 // This comes up when you have code like
3833 // int X = A < B;
3834 // if (X) ...
3835 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003836 // with a constant or another cast from the same type.
3837 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3838 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3839 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003840 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003841 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003842}
3843
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003844// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3845// We only handle extending casts so far.
3846//
3847Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3848 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3849 const Type *SrcTy = LHSCIOp->getType();
3850 const Type *DestTy = SCI.getOperand(0)->getType();
3851 Value *RHSCIOp;
3852
3853 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003854 return 0;
3855
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003856 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3857 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3858 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3859
3860 // Is this a sign or zero extension?
3861 bool isSignSrc = SrcTy->isSigned();
3862 bool isSignDest = DestTy->isSigned();
3863
3864 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3865 // Not an extension from the same type?
3866 RHSCIOp = CI->getOperand(0);
3867 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3868 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3869 // Compute the constant that would happen if we truncated to SrcTy then
3870 // reextended to DestTy.
3871 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3872
3873 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3874 RHSCIOp = Res;
3875 } else {
3876 // If the value cannot be represented in the shorter type, we cannot emit
3877 // a simple comparison.
3878 if (SCI.getOpcode() == Instruction::SetEQ)
3879 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3880 if (SCI.getOpcode() == Instruction::SetNE)
3881 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3882
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003883 // Evaluate the comparison for LT.
3884 Value *Result;
3885 if (DestTy->isSigned()) {
3886 // We're performing a signed comparison.
3887 if (isSignSrc) {
3888 // Signed extend and signed comparison.
3889 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3890 Result = ConstantBool::False;
3891 else
3892 Result = ConstantBool::True; // X < (large) --> true
3893 } else {
3894 // Unsigned extend and signed comparison.
3895 if (cast<ConstantSInt>(CI)->getValue() < 0)
3896 Result = ConstantBool::False;
3897 else
3898 Result = ConstantBool::True;
3899 }
3900 } else {
3901 // We're performing an unsigned comparison.
3902 if (!isSignSrc) {
3903 // Unsigned extend & compare -> always true.
3904 Result = ConstantBool::True;
3905 } else {
3906 // We're performing an unsigned comp with a sign extended value.
3907 // This is true if the input is >= 0. [aka >s -1]
3908 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3909 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3910 NegOne, SCI.getName()), SCI);
3911 }
Reid Spencer279fa252004-11-28 21:31:15 +00003912 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003913
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003914 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003915 if (SCI.getOpcode() == Instruction::SetLT) {
3916 return ReplaceInstUsesWith(SCI, Result);
3917 } else {
3918 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3919 if (Constant *CI = dyn_cast<Constant>(Result))
3920 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3921 else
3922 return BinaryOperator::createNot(Result);
3923 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003924 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003925 } else {
3926 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003927 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003928
Chris Lattner252a8452005-06-16 03:00:08 +00003929 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003930 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3931}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003932
Chris Lattnere8d6c602003-03-10 19:16:08 +00003933Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003934 assert(I.getOperand(1)->getType() == Type::UByteTy);
3935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003936 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003937
3938 // shl X, 0 == X and shr X, 0 == X
3939 // shl 0, X == 0 and shr 0, X == 0
3940 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003941 Op0 == Constant::getNullValue(Op0->getType()))
3942 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003943
Chris Lattner81a7a232004-10-16 18:11:37 +00003944 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3945 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003946 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003947 else // undef << X -> 0 AND undef >>u X -> 0
3948 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3949 }
3950 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003951 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003952 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3953 else
3954 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3955 }
3956
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003957 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3958 if (!isLeftShift)
3959 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3960 if (CSI->isAllOnesValue())
3961 return ReplaceInstUsesWith(I, CSI);
3962
Chris Lattner183b3362004-04-09 19:05:30 +00003963 // Try to fold constant and into select arguments.
3964 if (isa<Constant>(Op0))
3965 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003966 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003967 return R;
3968
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003969 // See if we can turn a signed shr into an unsigned shr.
3970 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003971 if (MaskedValueIsZero(Op0,
3972 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003973 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3974 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3975 I.getName()), I);
3976 return new CastInst(V, I.getType());
3977 }
3978 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003979
Chris Lattner14553932006-01-06 07:12:35 +00003980 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3981 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3982 return Res;
3983 return 0;
3984}
3985
3986Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3987 ShiftInst &I) {
3988 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00003989 bool isSignedShift = Op0->getType()->isSigned();
3990 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00003991
3992 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3993 // of a signed value.
3994 //
3995 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3996 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00003997 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00003998 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3999 else {
4000 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4001 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004002 }
Chris Lattner14553932006-01-06 07:12:35 +00004003 }
4004
4005 // ((X*C1) << C2) == (X * (C1 << C2))
4006 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4007 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4008 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4009 return BinaryOperator::createMul(BO->getOperand(0),
4010 ConstantExpr::getShl(BOOp, Op1));
4011
4012 // Try to fold constant and into select arguments.
4013 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4014 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4015 return R;
4016 if (isa<PHINode>(Op0))
4017 if (Instruction *NV = FoldOpIntoPhi(I))
4018 return NV;
4019
4020 if (Op0->hasOneUse()) {
4021 // If this is a SHL of a sign-extending cast, see if we can turn the input
4022 // into a zero extending cast (a simple strength reduction).
4023 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4024 const Type *SrcTy = CI->getOperand(0)->getType();
4025 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
4026 SrcTy->getPrimitiveSizeInBits() <
4027 CI->getType()->getPrimitiveSizeInBits()) {
4028 // We can change it to a zero extension if we are shifting out all of
4029 // the sign extended bits. To check this, form a mask of all of the
4030 // sign extend bits, then shift them left and see if we have anything
4031 // left.
4032 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
4033 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
4034 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
4035 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
4036 // If the shift is nuking all of the sign bits, change this to a
4037 // zero extension cast. To do this, cast the cast input to
4038 // unsigned, then to the requested size.
4039 Value *CastOp = CI->getOperand(0);
4040 Instruction *NC =
4041 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
4042 CI->getName()+".uns");
4043 NC = InsertNewInstBefore(NC, I);
4044 // Finally, insert a replacement for CI.
4045 NC = new CastInst(NC, CI->getType(), CI->getName());
4046 CI->setName("");
4047 NC = InsertNewInstBefore(NC, I);
4048 WorkList.push_back(CI); // Delete CI later.
4049 I.setOperand(0, NC);
4050 return &I; // The SHL operand was modified.
Chris Lattner86102b82005-01-01 16:22:27 +00004051 }
4052 }
Chris Lattner14553932006-01-06 07:12:35 +00004053 }
4054
4055 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4056 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4057 Value *V1, *V2;
4058 ConstantInt *CC;
4059 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004060 default: break;
4061 case Instruction::Add:
4062 case Instruction::And:
4063 case Instruction::Or:
4064 case Instruction::Xor:
4065 // These operators commute.
4066 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004067 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4068 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004069 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004070 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004071 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004072 Op0BO->getName());
4073 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004074 Instruction *X =
4075 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4076 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004077 InsertNewInstBefore(X, I); // (X + (Y << C))
4078 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004079 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004080 return BinaryOperator::createAnd(X, C2);
4081 }
Chris Lattner14553932006-01-06 07:12:35 +00004082
Chris Lattner797dee72005-09-18 06:30:59 +00004083 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4084 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4085 match(Op0BO->getOperand(1),
4086 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004087 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004088 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004089 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004090 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004091 Op0BO->getName());
4092 InsertNewInstBefore(YS, I); // (Y << C)
4093 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004094 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004095 V1->getName()+".mask");
4096 InsertNewInstBefore(XM, I); // X & (CC << C)
4097
4098 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4099 }
Chris Lattner14553932006-01-06 07:12:35 +00004100
Chris Lattner797dee72005-09-18 06:30:59 +00004101 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004102 case Instruction::Sub:
4103 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004104 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4105 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004106 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004107 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004108 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004109 Op0BO->getName());
4110 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004111 Instruction *X =
4112 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4113 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004114 InsertNewInstBefore(X, I); // (X + (Y << C))
4115 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004116 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004117 return BinaryOperator::createAnd(X, C2);
4118 }
Chris Lattner14553932006-01-06 07:12:35 +00004119
Chris Lattner797dee72005-09-18 06:30:59 +00004120 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4121 match(Op0BO->getOperand(0),
4122 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004123 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004124 cast<BinaryOperator>(Op0BO->getOperand(0))
4125 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004126 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004127 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004128 Op0BO->getName());
4129 InsertNewInstBefore(YS, I); // (Y << C)
4130 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004131 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004132 V1->getName()+".mask");
4133 InsertNewInstBefore(XM, I); // X & (CC << C)
4134
4135 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4136 }
Chris Lattner14553932006-01-06 07:12:35 +00004137
Chris Lattner27cb9db2005-09-18 05:12:10 +00004138 break;
Chris Lattner14553932006-01-06 07:12:35 +00004139 }
4140
4141
4142 // If the operand is an bitwise operator with a constant RHS, and the
4143 // shift is the only use, we can pull it out of the shift.
4144 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4145 bool isValid = true; // Valid only for And, Or, Xor
4146 bool highBitSet = false; // Transform if high bit of constant set?
4147
4148 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004149 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004150 case Instruction::Add:
4151 isValid = isLeftShift;
4152 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004153 case Instruction::Or:
4154 case Instruction::Xor:
4155 highBitSet = false;
4156 break;
4157 case Instruction::And:
4158 highBitSet = true;
4159 break;
Chris Lattner14553932006-01-06 07:12:35 +00004160 }
4161
4162 // If this is a signed shift right, and the high bit is modified
4163 // by the logical operation, do not perform the transformation.
4164 // The highBitSet boolean indicates the value of the high bit of
4165 // the constant which would cause it to be modified for this
4166 // operation.
4167 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004168 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004169 uint64_t Val = Op0C->getRawValue();
4170 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4171 }
4172
4173 if (isValid) {
4174 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4175
4176 Instruction *NewShift =
4177 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4178 Op0BO->getName());
4179 Op0BO->setName("");
4180 InsertNewInstBefore(NewShift, I);
4181
4182 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4183 NewRHS);
4184 }
4185 }
4186 }
4187 }
4188
Chris Lattnereb372a02006-01-06 07:52:12 +00004189 // Find out if this is a shift of a shift by a constant.
4190 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004191 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004192 ShiftOp = Op0SI;
4193 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4194 // If this is a noop-integer case of a shift instruction, use the shift.
4195 if (CI->getOperand(0)->getType()->isInteger() &&
4196 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4197 CI->getType()->getPrimitiveSizeInBits() &&
4198 isa<ShiftInst>(CI->getOperand(0))) {
4199 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4200 }
4201 }
4202
4203 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4204 // Find the operands and properties of the input shift. Note that the
4205 // signedness of the input shift may differ from the current shift if there
4206 // is a noop cast between the two.
4207 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4208 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004209 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004210
4211 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4212
4213 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4214 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4215
4216 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4217 if (isLeftShift == isShiftOfLeftShift) {
4218 // Do not fold these shifts if the first one is signed and the second one
4219 // is unsigned and this is a right shift. Further, don't do any folding
4220 // on them.
4221 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4222 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004223
Chris Lattnereb372a02006-01-06 07:52:12 +00004224 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4225 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4226 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004227
Chris Lattnereb372a02006-01-06 07:52:12 +00004228 Value *Op = ShiftOp->getOperand(0);
4229 if (isShiftOfSignedShift != isSignedShift)
4230 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4231 return new ShiftInst(I.getOpcode(), Op,
4232 ConstantUInt::get(Type::UByteTy, Amt));
4233 }
4234
4235 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4236 // signed types, we can only support the (A >> c1) << c2 configuration,
4237 // because it can not turn an arbitrary bit of A into a sign bit.
4238 if (isUnsignedShift || isLeftShift) {
4239 // Calculate bitmask for what gets shifted off the edge.
4240 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4241 if (isLeftShift)
4242 C = ConstantExpr::getShl(C, ShiftAmt1C);
4243 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004244 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004245
4246 Value *Op = ShiftOp->getOperand(0);
4247 if (isShiftOfSignedShift != isSignedShift)
4248 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4249
4250 Instruction *Mask =
4251 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4252 InsertNewInstBefore(Mask, I);
4253
4254 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004255 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004256 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004257 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004258 return new ShiftInst(I.getOpcode(), Mask,
4259 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004260 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4261 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4262 // Make sure to emit an unsigned shift right, not a signed one.
4263 Mask = InsertNewInstBefore(new CastInst(Mask,
4264 Mask->getType()->getUnsignedVersion(),
4265 Op->getName()), I);
4266 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004267 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004268 InsertNewInstBefore(Mask, I);
4269 return new CastInst(Mask, I.getType());
4270 } else {
4271 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4272 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4273 }
4274 } else {
4275 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4276 Op = InsertNewInstBefore(new CastInst(Mask,
4277 I.getType()->getSignedVersion(),
4278 Mask->getName()), I);
4279 Instruction *Shift =
4280 new ShiftInst(ShiftOp->getOpcode(), Op,
4281 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4282 InsertNewInstBefore(Shift, I);
4283
4284 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4285 C = ConstantExpr::getShl(C, Op1);
4286 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4287 InsertNewInstBefore(Mask, I);
4288 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004289 }
4290 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004291 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004292 // this case, C1 == C2 and C1 is 8, 16, or 32.
4293 if (ShiftAmt1 == ShiftAmt2) {
4294 const Type *SExtType = 0;
4295 switch (ShiftAmt1) {
4296 case 8 : SExtType = Type::SByteTy; break;
4297 case 16: SExtType = Type::ShortTy; break;
4298 case 32: SExtType = Type::IntTy; break;
4299 }
4300
4301 if (SExtType) {
4302 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4303 SExtType, "sext");
4304 InsertNewInstBefore(NewTrunc, I);
4305 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004306 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004307 }
Chris Lattner86102b82005-01-01 16:22:27 +00004308 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004309 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004310 return 0;
4311}
4312
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004313enum CastType {
4314 Noop = 0,
4315 Truncate = 1,
4316 Signext = 2,
4317 Zeroext = 3
4318};
4319
4320/// getCastType - In the future, we will split the cast instruction into these
4321/// various types. Until then, we have to do the analysis here.
4322static CastType getCastType(const Type *Src, const Type *Dest) {
4323 assert(Src->isIntegral() && Dest->isIntegral() &&
4324 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004325 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4326 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004327
4328 if (SrcSize == DestSize) return Noop;
4329 if (SrcSize > DestSize) return Truncate;
4330 if (Src->isSigned()) return Signext;
4331 return Zeroext;
4332}
4333
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004334
Chris Lattner48a44f72002-05-02 17:06:02 +00004335// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4336// instruction.
4337//
Chris Lattnere154abf2006-01-19 07:40:22 +00004338static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4339 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004340
Chris Lattner650b6da2002-08-02 20:00:25 +00004341 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004342 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004343 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004344 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004345 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004346
Chris Lattner4fbad962004-07-21 04:27:24 +00004347 // If we are casting between pointer and integer types, treat pointers as
4348 // integers of the appropriate size for the code below.
4349 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4350 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4351 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004352
Chris Lattner48a44f72002-05-02 17:06:02 +00004353 // Allow free casting and conversion of sizes as long as the sign doesn't
4354 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004355 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004356 CastType FirstCast = getCastType(SrcTy, MidTy);
4357 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004358
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004359 // Capture the effect of these two casts. If the result is a legal cast,
4360 // the CastType is stored here, otherwise a special code is used.
4361 static const unsigned CastResult[] = {
4362 // First cast is noop
4363 0, 1, 2, 3,
4364 // First cast is a truncate
4365 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4366 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004367 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004368 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004369 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004370 };
4371
4372 unsigned Result = CastResult[FirstCast*4+SecondCast];
4373 switch (Result) {
4374 default: assert(0 && "Illegal table value!");
4375 case 0:
4376 case 1:
4377 case 2:
4378 case 3:
4379 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4380 // truncates, we could eliminate more casts.
4381 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4382 case 4:
4383 return false; // Not possible to eliminate this here.
4384 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004385 // Sign or zero extend followed by truncate is always ok if the result
4386 // is a truncate or noop.
4387 CastType ResultCast = getCastType(SrcTy, DstTy);
4388 if (ResultCast == Noop || ResultCast == Truncate)
4389 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004390 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004391 // result will match the sign/zeroextendness of the result.
4392 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004393 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004394 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004395
4396 // If this is a cast from 'float -> double -> integer', cast from
4397 // 'float -> integer' directly, as the value isn't changed by the
4398 // float->double conversion.
4399 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4400 DstTy->isIntegral() &&
4401 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4402 return true;
4403
Chris Lattner48a44f72002-05-02 17:06:02 +00004404 return false;
4405}
4406
Chris Lattner11ffd592004-07-20 05:21:00 +00004407static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004408 if (V->getType() == Ty || isa<Constant>(V)) return false;
4409 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004410 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4411 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004412 return false;
4413 return true;
4414}
4415
4416/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4417/// InsertBefore instruction. This is specialized a bit to avoid inserting
4418/// casts that are known to not do anything...
4419///
4420Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4421 Instruction *InsertBefore) {
4422 if (V->getType() == DestTy) return V;
4423 if (Constant *C = dyn_cast<Constant>(V))
4424 return ConstantExpr::getCast(C, DestTy);
4425
4426 CastInst *CI = new CastInst(V, DestTy, V->getName());
4427 InsertNewInstBefore(CI, *InsertBefore);
4428 return CI;
4429}
Chris Lattner48a44f72002-05-02 17:06:02 +00004430
Chris Lattner8f663e82005-10-29 04:36:15 +00004431/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4432/// expression. If so, decompose it, returning some value X, such that Val is
4433/// X*Scale+Offset.
4434///
4435static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4436 unsigned &Offset) {
4437 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4438 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4439 Offset = CI->getValue();
4440 Scale = 1;
4441 return ConstantUInt::get(Type::UIntTy, 0);
4442 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4443 if (I->getNumOperands() == 2) {
4444 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4445 if (I->getOpcode() == Instruction::Shl) {
4446 // This is a value scaled by '1 << the shift amt'.
4447 Scale = 1U << CUI->getValue();
4448 Offset = 0;
4449 return I->getOperand(0);
4450 } else if (I->getOpcode() == Instruction::Mul) {
4451 // This value is scaled by 'CUI'.
4452 Scale = CUI->getValue();
4453 Offset = 0;
4454 return I->getOperand(0);
4455 } else if (I->getOpcode() == Instruction::Add) {
4456 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4457 // divisible by C2.
4458 unsigned SubScale;
4459 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4460 Offset);
4461 Offset += CUI->getValue();
4462 if (SubScale > 1 && (Offset % SubScale == 0)) {
4463 Scale = SubScale;
4464 return SubVal;
4465 }
4466 }
4467 }
4468 }
4469 }
4470
4471 // Otherwise, we can't look past this.
4472 Scale = 1;
4473 Offset = 0;
4474 return Val;
4475}
4476
4477
Chris Lattner216be912005-10-24 06:03:58 +00004478/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4479/// try to eliminate the cast by moving the type information into the alloc.
4480Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4481 AllocationInst &AI) {
4482 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004483 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004484
Chris Lattnerac87beb2005-10-24 06:22:12 +00004485 // Remove any uses of AI that are dead.
4486 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4487 std::vector<Instruction*> DeadUsers;
4488 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4489 Instruction *User = cast<Instruction>(*UI++);
4490 if (isInstructionTriviallyDead(User)) {
4491 while (UI != E && *UI == User)
4492 ++UI; // If this instruction uses AI more than once, don't break UI.
4493
4494 // Add operands to the worklist.
4495 AddUsesToWorkList(*User);
4496 ++NumDeadInst;
4497 DEBUG(std::cerr << "IC: DCE: " << *User);
4498
4499 User->eraseFromParent();
4500 removeFromWorkList(User);
4501 }
4502 }
4503
Chris Lattner216be912005-10-24 06:03:58 +00004504 // Get the type really allocated and the type casted to.
4505 const Type *AllocElTy = AI.getAllocatedType();
4506 const Type *CastElTy = PTy->getElementType();
4507 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004508
4509 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4510 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4511 if (CastElTyAlign < AllocElTyAlign) return 0;
4512
Chris Lattner46705b22005-10-24 06:35:18 +00004513 // If the allocation has multiple uses, only promote it if we are strictly
4514 // increasing the alignment of the resultant allocation. If we keep it the
4515 // same, we open the door to infinite loops of various kinds.
4516 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4517
Chris Lattner216be912005-10-24 06:03:58 +00004518 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4519 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004520 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004521
Chris Lattner8270c332005-10-29 03:19:53 +00004522 // See if we can satisfy the modulus by pulling a scale out of the array
4523 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004524 unsigned ArraySizeScale, ArrayOffset;
4525 Value *NumElements = // See if the array size is a decomposable linear expr.
4526 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4527
Chris Lattner8270c332005-10-29 03:19:53 +00004528 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4529 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004530 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4531 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004532
Chris Lattner8270c332005-10-29 03:19:53 +00004533 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4534 Value *Amt = 0;
4535 if (Scale == 1) {
4536 Amt = NumElements;
4537 } else {
4538 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4539 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4540 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4541 else if (Scale != 1) {
4542 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4543 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004544 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004545 }
4546
Chris Lattner8f663e82005-10-29 04:36:15 +00004547 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4548 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4549 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4550 Amt = InsertNewInstBefore(Tmp, AI);
4551 }
4552
Chris Lattner216be912005-10-24 06:03:58 +00004553 std::string Name = AI.getName(); AI.setName("");
4554 AllocationInst *New;
4555 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004556 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004557 else
Nate Begeman848622f2005-11-05 09:21:28 +00004558 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004559 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004560
4561 // If the allocation has multiple uses, insert a cast and change all things
4562 // that used it to use the new cast. This will also hack on CI, but it will
4563 // die soon.
4564 if (!AI.hasOneUse()) {
4565 AddUsesToWorkList(AI);
4566 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4567 InsertNewInstBefore(NewCast, AI);
4568 AI.replaceAllUsesWith(NewCast);
4569 }
Chris Lattner216be912005-10-24 06:03:58 +00004570 return ReplaceInstUsesWith(CI, New);
4571}
4572
4573
Chris Lattner48a44f72002-05-02 17:06:02 +00004574// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004575//
Chris Lattner113f4f42002-06-25 16:13:24 +00004576Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004577 Value *Src = CI.getOperand(0);
4578
Chris Lattner48a44f72002-05-02 17:06:02 +00004579 // If the user is casting a value to the same type, eliminate this cast
4580 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004581 if (CI.getType() == Src->getType())
4582 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004583
Chris Lattner81a7a232004-10-16 18:11:37 +00004584 if (isa<UndefValue>(Src)) // cast undef -> undef
4585 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4586
Chris Lattner48a44f72002-05-02 17:06:02 +00004587 // If casting the result of another cast instruction, try to eliminate this
4588 // one!
4589 //
Chris Lattner86102b82005-01-01 16:22:27 +00004590 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4591 Value *A = CSrc->getOperand(0);
4592 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4593 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004594 // This instruction now refers directly to the cast's src operand. This
4595 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004596 CI.setOperand(0, CSrc->getOperand(0));
4597 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004598 }
4599
Chris Lattner650b6da2002-08-02 20:00:25 +00004600 // If this is an A->B->A cast, and we are dealing with integral types, try
4601 // to convert this into a logical 'and' instruction.
4602 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004603 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004604 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004605 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004606 CSrc->getType()->getPrimitiveSizeInBits() <
4607 CI.getType()->getPrimitiveSizeInBits()&&
4608 A->getType()->getPrimitiveSizeInBits() ==
4609 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004610 assert(CSrc->getType() != Type::ULongTy &&
4611 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004612 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004613 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4614 AndValue);
4615 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4616 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4617 if (And->getType() != CI.getType()) {
4618 And->setName(CSrc->getName()+".mask");
4619 InsertNewInstBefore(And, CI);
4620 And = new CastInst(And, CI.getType());
4621 }
4622 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004623 }
4624 }
Chris Lattner2590e512006-02-07 06:56:34 +00004625
Chris Lattner03841652004-05-25 04:29:21 +00004626 // If this is a cast to bool, turn it into the appropriate setne instruction.
4627 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004628 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004629 Constant::getNullValue(CI.getOperand(0)->getType()));
4630
Chris Lattner2590e512006-02-07 06:56:34 +00004631 // See if we can simplify any instructions used by the LHS whose sole
4632 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004633 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4634 uint64_t KnownZero, KnownOne;
4635 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4636 KnownZero, KnownOne))
4637 return &CI;
4638 }
Chris Lattner2590e512006-02-07 06:56:34 +00004639
Chris Lattnerd0d51602003-06-21 23:12:02 +00004640 // If casting the result of a getelementptr instruction with no offset, turn
4641 // this into a cast of the original pointer!
4642 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004643 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004644 bool AllZeroOperands = true;
4645 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4646 if (!isa<Constant>(GEP->getOperand(i)) ||
4647 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4648 AllZeroOperands = false;
4649 break;
4650 }
4651 if (AllZeroOperands) {
4652 CI.setOperand(0, GEP->getOperand(0));
4653 return &CI;
4654 }
4655 }
4656
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004657 // If we are casting a malloc or alloca to a pointer to a type of the same
4658 // size, rewrite the allocation instruction to allocate the "right" type.
4659 //
4660 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004661 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4662 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004663
Chris Lattner86102b82005-01-01 16:22:27 +00004664 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4665 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4666 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004667 if (isa<PHINode>(Src))
4668 if (Instruction *NV = FoldOpIntoPhi(CI))
4669 return NV;
4670
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004671 // If the source value is an instruction with only this use, we can attempt to
4672 // propagate the cast into the instruction. Also, only handle integral types
4673 // for now.
4674 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004675 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004676 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4677 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004678 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4679 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004680
4681 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4682 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4683
4684 switch (SrcI->getOpcode()) {
4685 case Instruction::Add:
4686 case Instruction::Mul:
4687 case Instruction::And:
4688 case Instruction::Or:
4689 case Instruction::Xor:
4690 // If we are discarding information, or just changing the sign, rewrite.
4691 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4692 // Don't insert two casts if they cannot be eliminated. We allow two
4693 // casts to be inserted if the sizes are the same. This could only be
4694 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004695 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4696 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004697 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4698 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4699 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4700 ->getOpcode(), Op0c, Op1c);
4701 }
4702 }
Chris Lattner72086162005-05-06 02:07:39 +00004703
4704 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4705 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4706 Op1 == ConstantBool::True &&
4707 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4708 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4709 return BinaryOperator::createXor(New,
4710 ConstantInt::get(CI.getType(), 1));
4711 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004712 break;
4713 case Instruction::Shl:
4714 // Allow changing the sign of the source operand. Do not allow changing
4715 // the size of the shift, UNLESS the shift amount is a constant. We
4716 // mush not change variable sized shifts to a smaller size, because it
4717 // is undefined to shift more bits out than exist in the value.
4718 if (DestBitSize == SrcBitSize ||
4719 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4720 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4721 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4722 }
4723 break;
Chris Lattner87380412005-05-06 04:18:52 +00004724 case Instruction::Shr:
4725 // If this is a signed shr, and if all bits shifted in are about to be
4726 // truncated off, turn it into an unsigned shr to allow greater
4727 // simplifications.
4728 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4729 isa<ConstantInt>(Op1)) {
4730 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4731 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4732 // Convert to unsigned.
4733 Value *N1 = InsertOperandCastBefore(Op0,
4734 Op0->getType()->getUnsignedVersion(), &CI);
4735 // Insert the new shift, which is now unsigned.
4736 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4737 Op1, Src->getName()), CI);
4738 return new CastInst(N1, CI.getType());
4739 }
4740 }
4741 break;
4742
Chris Lattner809dfac2005-05-04 19:10:26 +00004743 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004744 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004745 if (Op1C->getRawValue() == 0) {
4746 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004747 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004748 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004749 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004750 if (MaskedValueIsZero(Op0,
4751 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner809dfac2005-05-04 19:10:26 +00004752 if (CI.getType() == Op0->getType())
4753 return ReplaceInstUsesWith(CI, Op0);
4754 else
4755 return new CastInst(Op0, CI.getType());
4756 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004757
4758 // If the input is an and with a single bit, shift then simplify.
4759 ConstantInt *AndRHS;
4760 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4761 if (AndRHS->getRawValue() &&
4762 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004763 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004764 // Perform an unsigned shr by shiftamt. Convert input to
4765 // unsigned if it is signed.
4766 Value *In = Op0;
4767 if (In->getType()->isSigned())
4768 In = InsertNewInstBefore(new CastInst(In,
4769 In->getType()->getUnsignedVersion(), In->getName()),CI);
4770 // Insert the shift to put the result in the low bit.
4771 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4772 ConstantInt::get(Type::UByteTy, ShiftAmt),
4773 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004774 if (CI.getType() == In->getType())
4775 return ReplaceInstUsesWith(CI, In);
4776 else
4777 return new CastInst(In, CI.getType());
4778 }
4779 }
4780 }
4781 break;
4782 case Instruction::SetEQ:
4783 // We if we are just checking for a seteq of a single bit and casting it
4784 // to an integer. If so, shift the bit to the appropriate place then
4785 // cast to integer to avoid the comparison.
4786 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4787 // Is Op1C a power of two or zero?
4788 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4789 // cast (X == 1) to int -> X iff X has only the low bit set.
4790 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004791 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004792 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004793 if (MaskedValueIsZero(Op0,
4794 cast<ConstantIntegral>(Not1)->getZExtValue())) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004795 if (CI.getType() == Op0->getType())
4796 return ReplaceInstUsesWith(CI, Op0);
4797 else
4798 return new CastInst(Op0, CI.getType());
4799 }
4800 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004801 }
4802 }
4803 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004804 }
4805 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004806
Chris Lattner260ab202002-04-18 17:39:14 +00004807 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004808}
4809
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004810/// GetSelectFoldableOperands - We want to turn code that looks like this:
4811/// %C = or %A, %B
4812/// %D = select %cond, %C, %A
4813/// into:
4814/// %C = select %cond, %B, 0
4815/// %D = or %A, %C
4816///
4817/// Assuming that the specified instruction is an operand to the select, return
4818/// a bitmask indicating which operands of this instruction are foldable if they
4819/// equal the other incoming value of the select.
4820///
4821static unsigned GetSelectFoldableOperands(Instruction *I) {
4822 switch (I->getOpcode()) {
4823 case Instruction::Add:
4824 case Instruction::Mul:
4825 case Instruction::And:
4826 case Instruction::Or:
4827 case Instruction::Xor:
4828 return 3; // Can fold through either operand.
4829 case Instruction::Sub: // Can only fold on the amount subtracted.
4830 case Instruction::Shl: // Can only fold on the shift amount.
4831 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004832 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004833 default:
4834 return 0; // Cannot fold
4835 }
4836}
4837
4838/// GetSelectFoldableConstant - For the same transformation as the previous
4839/// function, return the identity constant that goes into the select.
4840static Constant *GetSelectFoldableConstant(Instruction *I) {
4841 switch (I->getOpcode()) {
4842 default: assert(0 && "This cannot happen!"); abort();
4843 case Instruction::Add:
4844 case Instruction::Sub:
4845 case Instruction::Or:
4846 case Instruction::Xor:
4847 return Constant::getNullValue(I->getType());
4848 case Instruction::Shl:
4849 case Instruction::Shr:
4850 return Constant::getNullValue(Type::UByteTy);
4851 case Instruction::And:
4852 return ConstantInt::getAllOnesValue(I->getType());
4853 case Instruction::Mul:
4854 return ConstantInt::get(I->getType(), 1);
4855 }
4856}
4857
Chris Lattner411336f2005-01-19 21:50:18 +00004858/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4859/// have the same opcode and only one use each. Try to simplify this.
4860Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4861 Instruction *FI) {
4862 if (TI->getNumOperands() == 1) {
4863 // If this is a non-volatile load or a cast from the same type,
4864 // merge.
4865 if (TI->getOpcode() == Instruction::Cast) {
4866 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4867 return 0;
4868 } else {
4869 return 0; // unknown unary op.
4870 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004871
Chris Lattner411336f2005-01-19 21:50:18 +00004872 // Fold this by inserting a select from the input values.
4873 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4874 FI->getOperand(0), SI.getName()+".v");
4875 InsertNewInstBefore(NewSI, SI);
4876 return new CastInst(NewSI, TI->getType());
4877 }
4878
4879 // Only handle binary operators here.
4880 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4881 return 0;
4882
4883 // Figure out if the operations have any operands in common.
4884 Value *MatchOp, *OtherOpT, *OtherOpF;
4885 bool MatchIsOpZero;
4886 if (TI->getOperand(0) == FI->getOperand(0)) {
4887 MatchOp = TI->getOperand(0);
4888 OtherOpT = TI->getOperand(1);
4889 OtherOpF = FI->getOperand(1);
4890 MatchIsOpZero = true;
4891 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4892 MatchOp = TI->getOperand(1);
4893 OtherOpT = TI->getOperand(0);
4894 OtherOpF = FI->getOperand(0);
4895 MatchIsOpZero = false;
4896 } else if (!TI->isCommutative()) {
4897 return 0;
4898 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4899 MatchOp = TI->getOperand(0);
4900 OtherOpT = TI->getOperand(1);
4901 OtherOpF = FI->getOperand(0);
4902 MatchIsOpZero = true;
4903 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4904 MatchOp = TI->getOperand(1);
4905 OtherOpT = TI->getOperand(0);
4906 OtherOpF = FI->getOperand(1);
4907 MatchIsOpZero = true;
4908 } else {
4909 return 0;
4910 }
4911
4912 // If we reach here, they do have operations in common.
4913 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4914 OtherOpF, SI.getName()+".v");
4915 InsertNewInstBefore(NewSI, SI);
4916
4917 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4918 if (MatchIsOpZero)
4919 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4920 else
4921 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4922 } else {
4923 if (MatchIsOpZero)
4924 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4925 else
4926 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4927 }
4928}
4929
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004930Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004931 Value *CondVal = SI.getCondition();
4932 Value *TrueVal = SI.getTrueValue();
4933 Value *FalseVal = SI.getFalseValue();
4934
4935 // select true, X, Y -> X
4936 // select false, X, Y -> Y
4937 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004938 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004939 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004940 else {
4941 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004942 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004943 }
Chris Lattner533bc492004-03-30 19:37:13 +00004944
4945 // select C, X, X -> X
4946 if (TrueVal == FalseVal)
4947 return ReplaceInstUsesWith(SI, TrueVal);
4948
Chris Lattner81a7a232004-10-16 18:11:37 +00004949 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4950 return ReplaceInstUsesWith(SI, FalseVal);
4951 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4952 return ReplaceInstUsesWith(SI, TrueVal);
4953 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4954 if (isa<Constant>(TrueVal))
4955 return ReplaceInstUsesWith(SI, TrueVal);
4956 else
4957 return ReplaceInstUsesWith(SI, FalseVal);
4958 }
4959
Chris Lattner1c631e82004-04-08 04:43:23 +00004960 if (SI.getType() == Type::BoolTy)
4961 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4962 if (C == ConstantBool::True) {
4963 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004964 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004965 } else {
4966 // Change: A = select B, false, C --> A = and !B, C
4967 Value *NotCond =
4968 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4969 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004970 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004971 }
4972 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4973 if (C == ConstantBool::False) {
4974 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004975 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004976 } else {
4977 // Change: A = select B, C, true --> A = or !B, C
4978 Value *NotCond =
4979 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4980 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004981 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004982 }
4983 }
4984
Chris Lattner183b3362004-04-09 19:05:30 +00004985 // Selecting between two integer constants?
4986 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4987 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4988 // select C, 1, 0 -> cast C to int
4989 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4990 return new CastInst(CondVal, SI.getType());
4991 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4992 // select C, 0, 1 -> cast !C to int
4993 Value *NotCond =
4994 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004995 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004996 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004997 }
Chris Lattner35167c32004-06-09 07:59:58 +00004998
4999 // If one of the constants is zero (we know they can't both be) and we
5000 // have a setcc instruction with zero, and we have an 'and' with the
5001 // non-constant value, eliminate this whole mess. This corresponds to
5002 // cases like this: ((X & 27) ? 27 : 0)
5003 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5004 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5005 if ((IC->getOpcode() == Instruction::SetEQ ||
5006 IC->getOpcode() == Instruction::SetNE) &&
5007 isa<ConstantInt>(IC->getOperand(1)) &&
5008 cast<Constant>(IC->getOperand(1))->isNullValue())
5009 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5010 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005011 isa<ConstantInt>(ICA->getOperand(1)) &&
5012 (ICA->getOperand(1) == TrueValC ||
5013 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005014 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5015 // Okay, now we know that everything is set up, we just don't
5016 // know whether we have a setne or seteq and whether the true or
5017 // false val is the zero.
5018 bool ShouldNotVal = !TrueValC->isNullValue();
5019 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5020 Value *V = ICA;
5021 if (ShouldNotVal)
5022 V = InsertNewInstBefore(BinaryOperator::create(
5023 Instruction::Xor, V, ICA->getOperand(1)), SI);
5024 return ReplaceInstUsesWith(SI, V);
5025 }
Chris Lattner533bc492004-03-30 19:37:13 +00005026 }
Chris Lattner623fba12004-04-10 22:21:27 +00005027
5028 // See if we are selecting two values based on a comparison of the two values.
5029 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5030 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5031 // Transform (X == Y) ? X : Y -> Y
5032 if (SCI->getOpcode() == Instruction::SetEQ)
5033 return ReplaceInstUsesWith(SI, FalseVal);
5034 // Transform (X != Y) ? X : Y -> X
5035 if (SCI->getOpcode() == Instruction::SetNE)
5036 return ReplaceInstUsesWith(SI, TrueVal);
5037 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5038
5039 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5040 // Transform (X == Y) ? Y : X -> X
5041 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005042 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005043 // Transform (X != Y) ? Y : X -> Y
5044 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005045 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005046 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5047 }
5048 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005049
Chris Lattnera04c9042005-01-13 22:52:24 +00005050 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5051 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5052 if (TI->hasOneUse() && FI->hasOneUse()) {
5053 bool isInverse = false;
5054 Instruction *AddOp = 0, *SubOp = 0;
5055
Chris Lattner411336f2005-01-19 21:50:18 +00005056 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5057 if (TI->getOpcode() == FI->getOpcode())
5058 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5059 return IV;
5060
5061 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5062 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005063 if (TI->getOpcode() == Instruction::Sub &&
5064 FI->getOpcode() == Instruction::Add) {
5065 AddOp = FI; SubOp = TI;
5066 } else if (FI->getOpcode() == Instruction::Sub &&
5067 TI->getOpcode() == Instruction::Add) {
5068 AddOp = TI; SubOp = FI;
5069 }
5070
5071 if (AddOp) {
5072 Value *OtherAddOp = 0;
5073 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5074 OtherAddOp = AddOp->getOperand(1);
5075 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5076 OtherAddOp = AddOp->getOperand(0);
5077 }
5078
5079 if (OtherAddOp) {
5080 // So at this point we know we have:
5081 // select C, (add X, Y), (sub X, ?)
5082 // We can do the transform profitably if either 'Y' = '?' or '?' is
5083 // a constant.
5084 if (SubOp->getOperand(1) == AddOp ||
5085 isa<Constant>(SubOp->getOperand(1))) {
5086 Value *NegVal;
5087 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5088 NegVal = ConstantExpr::getNeg(C);
5089 } else {
5090 NegVal = InsertNewInstBefore(
5091 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
5092 }
5093
Chris Lattner51726c42005-01-14 17:35:12 +00005094 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00005095 Value *NewFalseOp = NegVal;
5096 if (AddOp != TI)
5097 std::swap(NewTrueOp, NewFalseOp);
5098 Instruction *NewSel =
5099 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00005100
Chris Lattnera04c9042005-01-13 22:52:24 +00005101 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00005102 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005103 }
5104 }
5105 }
5106 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005107
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005108 // See if we can fold the select into one of our operands.
5109 if (SI.getType()->isInteger()) {
5110 // See the comment above GetSelectFoldableOperands for a description of the
5111 // transformation we are doing here.
5112 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5113 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5114 !isa<Constant>(FalseVal))
5115 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5116 unsigned OpToFold = 0;
5117 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5118 OpToFold = 1;
5119 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5120 OpToFold = 2;
5121 }
5122
5123 if (OpToFold) {
5124 Constant *C = GetSelectFoldableConstant(TVI);
5125 std::string Name = TVI->getName(); TVI->setName("");
5126 Instruction *NewSel =
5127 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5128 Name);
5129 InsertNewInstBefore(NewSel, SI);
5130 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5131 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5132 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5133 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5134 else {
5135 assert(0 && "Unknown instruction!!");
5136 }
5137 }
5138 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005139
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005140 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5141 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5142 !isa<Constant>(TrueVal))
5143 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5144 unsigned OpToFold = 0;
5145 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5146 OpToFold = 1;
5147 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5148 OpToFold = 2;
5149 }
5150
5151 if (OpToFold) {
5152 Constant *C = GetSelectFoldableConstant(FVI);
5153 std::string Name = FVI->getName(); FVI->setName("");
5154 Instruction *NewSel =
5155 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5156 Name);
5157 InsertNewInstBefore(NewSel, SI);
5158 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5159 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5160 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5161 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5162 else {
5163 assert(0 && "Unknown instruction!!");
5164 }
5165 }
5166 }
5167 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005168
5169 if (BinaryOperator::isNot(CondVal)) {
5170 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5171 SI.setOperand(1, FalseVal);
5172 SI.setOperand(2, TrueVal);
5173 return &SI;
5174 }
5175
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005176 return 0;
5177}
5178
5179
Chris Lattnerc66b2232006-01-13 20:11:04 +00005180/// visitCallInst - CallInst simplification. This mostly only handles folding
5181/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5182/// the heavy lifting.
5183///
Chris Lattner970c33a2003-06-19 17:00:31 +00005184Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005185 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5186 if (!II) return visitCallSite(&CI);
5187
Chris Lattner51ea1272004-02-28 05:22:00 +00005188 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5189 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005190 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005191 bool Changed = false;
5192
5193 // memmove/cpy/set of zero bytes is a noop.
5194 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5195 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5196
5197 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005198
Chris Lattner00648e12004-10-12 04:52:52 +00005199 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5200 if (CI->getRawValue() == 1) {
5201 // Replace the instruction with just byte operations. We would
5202 // transform other cases to loads/stores, but we don't know if
5203 // alignment is sufficient.
5204 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005205 }
5206
Chris Lattner00648e12004-10-12 04:52:52 +00005207 // If we have a memmove and the source operation is a constant global,
5208 // then the source and dest pointers can't alias, so we can change this
5209 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005210 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00005211 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5212 if (GVSrc->isConstant()) {
5213 Module *M = CI.getParent()->getParent()->getParent();
5214 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
5215 CI.getCalledFunction()->getFunctionType());
5216 CI.setOperand(0, MemCpy);
5217 Changed = true;
5218 }
5219
Chris Lattnerc66b2232006-01-13 20:11:04 +00005220 if (Changed) return II;
5221 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00005222 // If this stoppoint is at the same source location as the previous
5223 // stoppoint in the chain, it is not needed.
5224 if (DbgStopPointInst *PrevSPI =
5225 dyn_cast<DbgStopPointInst>(SPI->getChain()))
5226 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
5227 SPI->getColNo() == PrevSPI->getColNo()) {
5228 SPI->replaceAllUsesWith(PrevSPI);
5229 return EraseInstFromFunction(CI);
5230 }
Chris Lattner503221f2006-01-13 21:28:09 +00005231 } else {
5232 switch (II->getIntrinsicID()) {
5233 default: break;
5234 case Intrinsic::stackrestore: {
5235 // If the save is right next to the restore, remove the restore. This can
5236 // happen when variable allocas are DCE'd.
5237 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5238 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5239 BasicBlock::iterator BI = SS;
5240 if (&*++BI == II)
5241 return EraseInstFromFunction(CI);
5242 }
5243 }
5244
5245 // If the stack restore is in a return/unwind block and if there are no
5246 // allocas or calls between the restore and the return, nuke the restore.
5247 TerminatorInst *TI = II->getParent()->getTerminator();
5248 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5249 BasicBlock::iterator BI = II;
5250 bool CannotRemove = false;
5251 for (++BI; &*BI != TI; ++BI) {
5252 if (isa<AllocaInst>(BI) ||
5253 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5254 CannotRemove = true;
5255 break;
5256 }
5257 }
5258 if (!CannotRemove)
5259 return EraseInstFromFunction(CI);
5260 }
5261 break;
5262 }
5263 }
Chris Lattner00648e12004-10-12 04:52:52 +00005264 }
5265
Chris Lattnerc66b2232006-01-13 20:11:04 +00005266 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005267}
5268
5269// InvokeInst simplification
5270//
5271Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005272 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005273}
5274
Chris Lattneraec3d942003-10-07 22:32:43 +00005275// visitCallSite - Improvements for call and invoke instructions.
5276//
5277Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005278 bool Changed = false;
5279
5280 // If the callee is a constexpr cast of a function, attempt to move the cast
5281 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005282 if (transformConstExprCastCall(CS)) return 0;
5283
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005284 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005285
Chris Lattner61d9d812005-05-13 07:09:09 +00005286 if (Function *CalleeF = dyn_cast<Function>(Callee))
5287 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5288 Instruction *OldCall = CS.getInstruction();
5289 // If the call and callee calling conventions don't match, this call must
5290 // be unreachable, as the call is undefined.
5291 new StoreInst(ConstantBool::True,
5292 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5293 if (!OldCall->use_empty())
5294 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5295 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5296 return EraseInstFromFunction(*OldCall);
5297 return 0;
5298 }
5299
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005300 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5301 // This instruction is not reachable, just remove it. We insert a store to
5302 // undef so that we know that this code is not reachable, despite the fact
5303 // that we can't modify the CFG here.
5304 new StoreInst(ConstantBool::True,
5305 UndefValue::get(PointerType::get(Type::BoolTy)),
5306 CS.getInstruction());
5307
5308 if (!CS.getInstruction()->use_empty())
5309 CS.getInstruction()->
5310 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5311
5312 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5313 // Don't break the CFG, insert a dummy cond branch.
5314 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5315 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005316 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005317 return EraseInstFromFunction(*CS.getInstruction());
5318 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005319
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005320 const PointerType *PTy = cast<PointerType>(Callee->getType());
5321 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5322 if (FTy->isVarArg()) {
5323 // See if we can optimize any arguments passed through the varargs area of
5324 // the call.
5325 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5326 E = CS.arg_end(); I != E; ++I)
5327 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5328 // If this cast does not effect the value passed through the varargs
5329 // area, we can eliminate the use of the cast.
5330 Value *Op = CI->getOperand(0);
5331 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5332 *I = Op;
5333 Changed = true;
5334 }
5335 }
5336 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005337
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005338 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005339}
5340
Chris Lattner970c33a2003-06-19 17:00:31 +00005341// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5342// attempt to move the cast to the arguments of the call/invoke.
5343//
5344bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5345 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5346 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005347 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005348 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005349 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005350 Instruction *Caller = CS.getInstruction();
5351
5352 // Okay, this is a cast from a function to a different type. Unless doing so
5353 // would cause a type conversion of one of our arguments, change this call to
5354 // be a direct call with arguments casted to the appropriate types.
5355 //
5356 const FunctionType *FT = Callee->getFunctionType();
5357 const Type *OldRetTy = Caller->getType();
5358
Chris Lattner1f7942f2004-01-14 06:06:08 +00005359 // Check to see if we are changing the return type...
5360 if (OldRetTy != FT->getReturnType()) {
5361 if (Callee->isExternal() &&
5362 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5363 !Caller->use_empty())
5364 return false; // Cannot transform this return value...
5365
5366 // If the callsite is an invoke instruction, and the return value is used by
5367 // a PHI node in a successor, we cannot change the return type of the call
5368 // because there is no place to put the cast instruction (without breaking
5369 // the critical edge). Bail out in this case.
5370 if (!Caller->use_empty())
5371 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5372 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5373 UI != E; ++UI)
5374 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5375 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005376 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005377 return false;
5378 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005379
5380 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5381 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005382
Chris Lattner970c33a2003-06-19 17:00:31 +00005383 CallSite::arg_iterator AI = CS.arg_begin();
5384 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5385 const Type *ParamTy = FT->getParamType(i);
5386 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005387 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005388 }
5389
5390 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5391 Callee->isExternal())
5392 return false; // Do not delete arguments unless we have a function body...
5393
5394 // Okay, we decided that this is a safe thing to do: go ahead and start
5395 // inserting cast instructions as necessary...
5396 std::vector<Value*> Args;
5397 Args.reserve(NumActualArgs);
5398
5399 AI = CS.arg_begin();
5400 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5401 const Type *ParamTy = FT->getParamType(i);
5402 if ((*AI)->getType() == ParamTy) {
5403 Args.push_back(*AI);
5404 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005405 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5406 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005407 }
5408 }
5409
5410 // If the function takes more arguments than the call was taking, add them
5411 // now...
5412 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5413 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5414
5415 // If we are removing arguments to the function, emit an obnoxious warning...
5416 if (FT->getNumParams() < NumActualArgs)
5417 if (!FT->isVarArg()) {
5418 std::cerr << "WARNING: While resolving call to function '"
5419 << Callee->getName() << "' arguments were dropped!\n";
5420 } else {
5421 // Add all of the arguments in their promoted form to the arg list...
5422 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5423 const Type *PTy = getPromotedType((*AI)->getType());
5424 if (PTy != (*AI)->getType()) {
5425 // Must promote to pass through va_arg area!
5426 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5427 InsertNewInstBefore(Cast, *Caller);
5428 Args.push_back(Cast);
5429 } else {
5430 Args.push_back(*AI);
5431 }
5432 }
5433 }
5434
5435 if (FT->getReturnType() == Type::VoidTy)
5436 Caller->setName(""); // Void type should not have a name...
5437
5438 Instruction *NC;
5439 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005440 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005441 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005442 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005443 } else {
5444 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005445 if (cast<CallInst>(Caller)->isTailCall())
5446 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005447 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005448 }
5449
5450 // Insert a cast of the return type as necessary...
5451 Value *NV = NC;
5452 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5453 if (NV->getType() != Type::VoidTy) {
5454 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005455
5456 // If this is an invoke instruction, we should insert it after the first
5457 // non-phi, instruction in the normal successor block.
5458 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5459 BasicBlock::iterator I = II->getNormalDest()->begin();
5460 while (isa<PHINode>(I)) ++I;
5461 InsertNewInstBefore(NC, *I);
5462 } else {
5463 // Otherwise, it's a call, just insert cast right after the call instr
5464 InsertNewInstBefore(NC, *Caller);
5465 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005466 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005467 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005468 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005469 }
5470 }
5471
5472 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5473 Caller->replaceAllUsesWith(NV);
5474 Caller->getParent()->getInstList().erase(Caller);
5475 removeFromWorkList(Caller);
5476 return true;
5477}
5478
5479
Chris Lattner7515cab2004-11-14 19:13:23 +00005480// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5481// operator and they all are only used by the PHI, PHI together their
5482// inputs, and do the operation once, to the result of the PHI.
5483Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5484 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5485
5486 // Scan the instruction, looking for input operations that can be folded away.
5487 // If all input operands to the phi are the same instruction (e.g. a cast from
5488 // the same type or "+42") we can pull the operation through the PHI, reducing
5489 // code size and simplifying code.
5490 Constant *ConstantOp = 0;
5491 const Type *CastSrcTy = 0;
5492 if (isa<CastInst>(FirstInst)) {
5493 CastSrcTy = FirstInst->getOperand(0)->getType();
5494 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5495 // Can fold binop or shift if the RHS is a constant.
5496 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5497 if (ConstantOp == 0) return 0;
5498 } else {
5499 return 0; // Cannot fold this operation.
5500 }
5501
5502 // Check to see if all arguments are the same operation.
5503 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5504 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5505 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5506 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5507 return 0;
5508 if (CastSrcTy) {
5509 if (I->getOperand(0)->getType() != CastSrcTy)
5510 return 0; // Cast operation must match.
5511 } else if (I->getOperand(1) != ConstantOp) {
5512 return 0;
5513 }
5514 }
5515
5516 // Okay, they are all the same operation. Create a new PHI node of the
5517 // correct type, and PHI together all of the LHS's of the instructions.
5518 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5519 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005520 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005521
5522 Value *InVal = FirstInst->getOperand(0);
5523 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005524
5525 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005526 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5527 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5528 if (NewInVal != InVal)
5529 InVal = 0;
5530 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5531 }
5532
5533 Value *PhiVal;
5534 if (InVal) {
5535 // The new PHI unions all of the same values together. This is really
5536 // common, so we handle it intelligently here for compile-time speed.
5537 PhiVal = InVal;
5538 delete NewPN;
5539 } else {
5540 InsertNewInstBefore(NewPN, PN);
5541 PhiVal = NewPN;
5542 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005543
Chris Lattner7515cab2004-11-14 19:13:23 +00005544 // Insert and return the new operation.
5545 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005546 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005547 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005548 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005549 else
5550 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005551 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005552}
Chris Lattner48a44f72002-05-02 17:06:02 +00005553
Chris Lattner71536432005-01-17 05:10:15 +00005554/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5555/// that is dead.
5556static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5557 if (PN->use_empty()) return true;
5558 if (!PN->hasOneUse()) return false;
5559
5560 // Remember this node, and if we find the cycle, return.
5561 if (!PotentiallyDeadPHIs.insert(PN).second)
5562 return true;
5563
5564 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5565 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005566
Chris Lattner71536432005-01-17 05:10:15 +00005567 return false;
5568}
5569
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005570// PHINode simplification
5571//
Chris Lattner113f4f42002-06-25 16:13:24 +00005572Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005573 if (Value *V = PN.hasConstantValue())
5574 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005575
5576 // If the only user of this instruction is a cast instruction, and all of the
5577 // incoming values are constants, change this PHI to merge together the casted
5578 // constants.
5579 if (PN.hasOneUse())
5580 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5581 if (CI->getType() != PN.getType()) { // noop casts will be folded
5582 bool AllConstant = true;
5583 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5584 if (!isa<Constant>(PN.getIncomingValue(i))) {
5585 AllConstant = false;
5586 break;
5587 }
5588 if (AllConstant) {
5589 // Make a new PHI with all casted values.
5590 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5591 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5592 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5593 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5594 PN.getIncomingBlock(i));
5595 }
5596
5597 // Update the cast instruction.
5598 CI->setOperand(0, New);
5599 WorkList.push_back(CI); // revisit the cast instruction to fold.
5600 WorkList.push_back(New); // Make sure to revisit the new Phi
5601 return &PN; // PN is now dead!
5602 }
5603 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005604
5605 // If all PHI operands are the same operation, pull them through the PHI,
5606 // reducing code size.
5607 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5608 PN.getIncomingValue(0)->hasOneUse())
5609 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5610 return Result;
5611
Chris Lattner71536432005-01-17 05:10:15 +00005612 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5613 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5614 // PHI)... break the cycle.
5615 if (PN.hasOneUse())
5616 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5617 std::set<PHINode*> PotentiallyDeadPHIs;
5618 PotentiallyDeadPHIs.insert(&PN);
5619 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5620 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5621 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005622
Chris Lattner91daeb52003-12-19 05:58:40 +00005623 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005624}
5625
Chris Lattner69193f92004-04-05 01:30:19 +00005626static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5627 Instruction *InsertPoint,
5628 InstCombiner *IC) {
5629 unsigned PS = IC->getTargetData().getPointerSize();
5630 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005631 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5632 // We must insert a cast to ensure we sign-extend.
5633 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5634 V->getName()), *InsertPoint);
5635 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5636 *InsertPoint);
5637}
5638
Chris Lattner48a44f72002-05-02 17:06:02 +00005639
Chris Lattner113f4f42002-06-25 16:13:24 +00005640Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005641 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005642 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005643 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005644 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005645 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005646
Chris Lattner81a7a232004-10-16 18:11:37 +00005647 if (isa<UndefValue>(GEP.getOperand(0)))
5648 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5649
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005650 bool HasZeroPointerIndex = false;
5651 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5652 HasZeroPointerIndex = C->isNullValue();
5653
5654 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005655 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005656
Chris Lattner69193f92004-04-05 01:30:19 +00005657 // Eliminate unneeded casts for indices.
5658 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005659 gep_type_iterator GTI = gep_type_begin(GEP);
5660 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5661 if (isa<SequentialType>(*GTI)) {
5662 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5663 Value *Src = CI->getOperand(0);
5664 const Type *SrcTy = Src->getType();
5665 const Type *DestTy = CI->getType();
5666 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005667 if (SrcTy->getPrimitiveSizeInBits() ==
5668 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005669 // We can always eliminate a cast from ulong or long to the other.
5670 // We can always eliminate a cast from uint to int or the other on
5671 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005672 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005673 MadeChange = true;
5674 GEP.setOperand(i, Src);
5675 }
5676 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5677 SrcTy->getPrimitiveSize() == 4) {
5678 // We can always eliminate a cast from int to [u]long. We can
5679 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5680 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005681 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005682 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005683 MadeChange = true;
5684 GEP.setOperand(i, Src);
5685 }
Chris Lattner69193f92004-04-05 01:30:19 +00005686 }
5687 }
5688 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005689 // If we are using a wider index than needed for this platform, shrink it
5690 // to what we need. If the incoming value needs a cast instruction,
5691 // insert it. This explicit cast can make subsequent optimizations more
5692 // obvious.
5693 Value *Op = GEP.getOperand(i);
5694 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005695 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005696 GEP.setOperand(i, ConstantExpr::getCast(C,
5697 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005698 MadeChange = true;
5699 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005700 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5701 Op->getName()), GEP);
5702 GEP.setOperand(i, Op);
5703 MadeChange = true;
5704 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005705
5706 // If this is a constant idx, make sure to canonicalize it to be a signed
5707 // operand, otherwise CSE and other optimizations are pessimized.
5708 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5709 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5710 CUI->getType()->getSignedVersion()));
5711 MadeChange = true;
5712 }
Chris Lattner69193f92004-04-05 01:30:19 +00005713 }
5714 if (MadeChange) return &GEP;
5715
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005716 // Combine Indices - If the source pointer to this getelementptr instruction
5717 // is a getelementptr instruction, combine the indices of the two
5718 // getelementptr instructions into a single instruction.
5719 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005720 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005721 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005722 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005723
5724 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005725 // Note that if our source is a gep chain itself that we wait for that
5726 // chain to be resolved before we perform this transformation. This
5727 // avoids us creating a TON of code in some cases.
5728 //
5729 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5730 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5731 return 0; // Wait until our source is folded to completion.
5732
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005733 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005734
5735 // Find out whether the last index in the source GEP is a sequential idx.
5736 bool EndsWithSequential = false;
5737 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5738 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005739 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005740
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005741 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005742 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005743 // Replace: gep (gep %P, long B), long A, ...
5744 // With: T = long A+B; gep %P, T, ...
5745 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005746 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005747 if (SO1 == Constant::getNullValue(SO1->getType())) {
5748 Sum = GO1;
5749 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5750 Sum = SO1;
5751 } else {
5752 // If they aren't the same type, convert both to an integer of the
5753 // target's pointer size.
5754 if (SO1->getType() != GO1->getType()) {
5755 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5756 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5757 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5758 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5759 } else {
5760 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005761 if (SO1->getType()->getPrimitiveSize() == PS) {
5762 // Convert GO1 to SO1's type.
5763 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5764
5765 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5766 // Convert SO1 to GO1's type.
5767 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5768 } else {
5769 const Type *PT = TD->getIntPtrType();
5770 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5771 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5772 }
5773 }
5774 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005775 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5776 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5777 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005778 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5779 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005780 }
Chris Lattner69193f92004-04-05 01:30:19 +00005781 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005782
5783 // Recycle the GEP we already have if possible.
5784 if (SrcGEPOperands.size() == 2) {
5785 GEP.setOperand(0, SrcGEPOperands[0]);
5786 GEP.setOperand(1, Sum);
5787 return &GEP;
5788 } else {
5789 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5790 SrcGEPOperands.end()-1);
5791 Indices.push_back(Sum);
5792 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5793 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005794 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005795 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005796 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005797 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005798 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5799 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005800 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5801 }
5802
5803 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005804 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005805
Chris Lattner5f667a62004-05-07 22:09:22 +00005806 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005807 // GEP of global variable. If all of the indices for this GEP are
5808 // constants, we can promote this to a constexpr instead of an instruction.
5809
5810 // Scan for nonconstants...
5811 std::vector<Constant*> Indices;
5812 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5813 for (; I != E && isa<Constant>(*I); ++I)
5814 Indices.push_back(cast<Constant>(*I));
5815
5816 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005817 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005818
5819 // Replace all uses of the GEP with the new constexpr...
5820 return ReplaceInstUsesWith(GEP, CE);
5821 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005822 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5823 if (!isa<PointerType>(X->getType())) {
5824 // Not interesting. Source pointer must be a cast from pointer.
5825 } else if (HasZeroPointerIndex) {
5826 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5827 // into : GEP [10 x ubyte]* X, long 0, ...
5828 //
5829 // This occurs when the program declares an array extern like "int X[];"
5830 //
5831 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5832 const PointerType *XTy = cast<PointerType>(X->getType());
5833 if (const ArrayType *XATy =
5834 dyn_cast<ArrayType>(XTy->getElementType()))
5835 if (const ArrayType *CATy =
5836 dyn_cast<ArrayType>(CPTy->getElementType()))
5837 if (CATy->getElementType() == XATy->getElementType()) {
5838 // At this point, we know that the cast source type is a pointer
5839 // to an array of the same type as the destination pointer
5840 // array. Because the array type is never stepped over (there
5841 // is a leading zero) we can fold the cast into this GEP.
5842 GEP.setOperand(0, X);
5843 return &GEP;
5844 }
5845 } else if (GEP.getNumOperands() == 2) {
5846 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005847 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5848 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005849 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5850 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5851 if (isa<ArrayType>(SrcElTy) &&
5852 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5853 TD->getTypeSize(ResElTy)) {
5854 Value *V = InsertNewInstBefore(
5855 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5856 GEP.getOperand(1), GEP.getName()), GEP);
5857 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005858 }
Chris Lattner2a893292005-09-13 18:36:04 +00005859
5860 // Transform things like:
5861 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5862 // (where tmp = 8*tmp2) into:
5863 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5864
5865 if (isa<ArrayType>(SrcElTy) &&
5866 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5867 uint64_t ArrayEltSize =
5868 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5869
5870 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5871 // allow either a mul, shift, or constant here.
5872 Value *NewIdx = 0;
5873 ConstantInt *Scale = 0;
5874 if (ArrayEltSize == 1) {
5875 NewIdx = GEP.getOperand(1);
5876 Scale = ConstantInt::get(NewIdx->getType(), 1);
5877 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005878 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005879 Scale = CI;
5880 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5881 if (Inst->getOpcode() == Instruction::Shl &&
5882 isa<ConstantInt>(Inst->getOperand(1))) {
5883 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5884 if (Inst->getType()->isSigned())
5885 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5886 else
5887 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5888 NewIdx = Inst->getOperand(0);
5889 } else if (Inst->getOpcode() == Instruction::Mul &&
5890 isa<ConstantInt>(Inst->getOperand(1))) {
5891 Scale = cast<ConstantInt>(Inst->getOperand(1));
5892 NewIdx = Inst->getOperand(0);
5893 }
5894 }
5895
5896 // If the index will be to exactly the right offset with the scale taken
5897 // out, perform the transformation.
5898 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5899 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5900 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005901 (int64_t)C->getRawValue() /
5902 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005903 else
5904 Scale = ConstantUInt::get(Scale->getType(),
5905 Scale->getRawValue() / ArrayEltSize);
5906 if (Scale->getRawValue() != 1) {
5907 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5908 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5909 NewIdx = InsertNewInstBefore(Sc, GEP);
5910 }
5911
5912 // Insert the new GEP instruction.
5913 Instruction *Idx =
5914 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5915 NewIdx, GEP.getName());
5916 Idx = InsertNewInstBefore(Idx, GEP);
5917 return new CastInst(Idx, GEP.getType());
5918 }
5919 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005920 }
Chris Lattnerca081252001-12-14 16:52:21 +00005921 }
5922
Chris Lattnerca081252001-12-14 16:52:21 +00005923 return 0;
5924}
5925
Chris Lattner1085bdf2002-11-04 16:18:53 +00005926Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5927 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5928 if (AI.isArrayAllocation()) // Check C != 1
5929 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5930 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005931 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005932
5933 // Create and insert the replacement instruction...
5934 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005935 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005936 else {
5937 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005938 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005939 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005940
5941 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005942
Chris Lattner1085bdf2002-11-04 16:18:53 +00005943 // Scan to the end of the allocation instructions, to skip over a block of
5944 // allocas if possible...
5945 //
5946 BasicBlock::iterator It = New;
5947 while (isa<AllocationInst>(*It)) ++It;
5948
5949 // Now that I is pointing to the first non-allocation-inst in the block,
5950 // insert our getelementptr instruction...
5951 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005952 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5953 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5954 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005955
5956 // Now make everything use the getelementptr instead of the original
5957 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005958 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005959 } else if (isa<UndefValue>(AI.getArraySize())) {
5960 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005961 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005962
5963 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5964 // Note that we only do this for alloca's, because malloc should allocate and
5965 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005966 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005967 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005968 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5969
Chris Lattner1085bdf2002-11-04 16:18:53 +00005970 return 0;
5971}
5972
Chris Lattner8427bff2003-12-07 01:24:23 +00005973Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5974 Value *Op = FI.getOperand(0);
5975
5976 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5977 if (CastInst *CI = dyn_cast<CastInst>(Op))
5978 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5979 FI.setOperand(0, CI->getOperand(0));
5980 return &FI;
5981 }
5982
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005983 // free undef -> unreachable.
5984 if (isa<UndefValue>(Op)) {
5985 // Insert a new store to null because we cannot modify the CFG here.
5986 new StoreInst(ConstantBool::True,
5987 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5988 return EraseInstFromFunction(FI);
5989 }
5990
Chris Lattnerf3a36602004-02-28 04:57:37 +00005991 // If we have 'free null' delete the instruction. This can happen in stl code
5992 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005993 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005994 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005995
Chris Lattner8427bff2003-12-07 01:24:23 +00005996 return 0;
5997}
5998
5999
Chris Lattner72684fe2005-01-31 05:51:45 +00006000/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006001static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6002 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006003 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006004
6005 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006006 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006007 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006008
6009 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6010 // If the source is an array, the code below will not succeed. Check to
6011 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6012 // constants.
6013 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6014 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6015 if (ASrcTy->getNumElements() != 0) {
6016 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6017 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6018 SrcTy = cast<PointerType>(CastOp->getType());
6019 SrcPTy = SrcTy->getElementType();
6020 }
6021
6022 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006023 // Do not allow turning this into a load of an integer, which is then
6024 // casted to a pointer, this pessimizes pointer analysis a lot.
6025 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006026 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006027 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006028
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006029 // Okay, we are casting from one integer or pointer type to another of
6030 // the same size. Instead of casting the pointer before the load, cast
6031 // the result of the loaded value.
6032 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6033 CI->getName(),
6034 LI.isVolatile()),LI);
6035 // Now cast the result of the load.
6036 return new CastInst(NewLoad, LI.getType());
6037 }
Chris Lattner35e24772004-07-13 01:49:43 +00006038 }
6039 }
6040 return 0;
6041}
6042
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006043/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006044/// from this value cannot trap. If it is not obviously safe to load from the
6045/// specified pointer, we do a quick local scan of the basic block containing
6046/// ScanFrom, to determine if the address is already accessed.
6047static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6048 // If it is an alloca or global variable, it is always safe to load from.
6049 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6050
6051 // Otherwise, be a little bit agressive by scanning the local block where we
6052 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006053 // from/to. If so, the previous load or store would have already trapped,
6054 // so there is no harm doing an extra load (also, CSE will later eliminate
6055 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006056 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6057
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006058 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006059 --BBI;
6060
6061 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6062 if (LI->getOperand(0) == V) return true;
6063 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6064 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006065
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006066 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006067 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006068}
6069
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006070Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6071 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006072
Chris Lattnera9d84e32005-05-01 04:24:53 +00006073 // load (cast X) --> cast (load X) iff safe
6074 if (CastInst *CI = dyn_cast<CastInst>(Op))
6075 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6076 return Res;
6077
6078 // None of the following transforms are legal for volatile loads.
6079 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006080
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006081 if (&LI.getParent()->front() != &LI) {
6082 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006083 // If the instruction immediately before this is a store to the same
6084 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006085 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6086 if (SI->getOperand(1) == LI.getOperand(0))
6087 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006088 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6089 if (LIB->getOperand(0) == LI.getOperand(0))
6090 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006091 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006092
6093 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6094 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6095 isa<UndefValue>(GEPI->getOperand(0))) {
6096 // Insert a new store to null instruction before the load to indicate
6097 // that this code is not reachable. We do this instead of inserting
6098 // an unreachable instruction directly because we cannot modify the
6099 // CFG.
6100 new StoreInst(UndefValue::get(LI.getType()),
6101 Constant::getNullValue(Op->getType()), &LI);
6102 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6103 }
6104
Chris Lattner81a7a232004-10-16 18:11:37 +00006105 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006106 // load null/undef -> undef
6107 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006108 // Insert a new store to null instruction before the load to indicate that
6109 // this code is not reachable. We do this instead of inserting an
6110 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006111 new StoreInst(UndefValue::get(LI.getType()),
6112 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006113 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006114 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006115
Chris Lattner81a7a232004-10-16 18:11:37 +00006116 // Instcombine load (constant global) into the value loaded.
6117 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6118 if (GV->isConstant() && !GV->isExternal())
6119 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006120
Chris Lattner81a7a232004-10-16 18:11:37 +00006121 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6122 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6123 if (CE->getOpcode() == Instruction::GetElementPtr) {
6124 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6125 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006126 if (Constant *V =
6127 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006128 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006129 if (CE->getOperand(0)->isNullValue()) {
6130 // Insert a new store to null instruction before the load to indicate
6131 // that this code is not reachable. We do this instead of inserting
6132 // an unreachable instruction directly because we cannot modify the
6133 // CFG.
6134 new StoreInst(UndefValue::get(LI.getType()),
6135 Constant::getNullValue(Op->getType()), &LI);
6136 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6137 }
6138
Chris Lattner81a7a232004-10-16 18:11:37 +00006139 } else if (CE->getOpcode() == Instruction::Cast) {
6140 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6141 return Res;
6142 }
6143 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006144
Chris Lattnera9d84e32005-05-01 04:24:53 +00006145 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006146 // Change select and PHI nodes to select values instead of addresses: this
6147 // helps alias analysis out a lot, allows many others simplifications, and
6148 // exposes redundancy in the code.
6149 //
6150 // Note that we cannot do the transformation unless we know that the
6151 // introduced loads cannot trap! Something like this is valid as long as
6152 // the condition is always false: load (select bool %C, int* null, int* %G),
6153 // but it would not be valid if we transformed it to load from null
6154 // unconditionally.
6155 //
6156 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6157 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006158 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6159 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006160 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006161 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006162 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006163 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006164 return new SelectInst(SI->getCondition(), V1, V2);
6165 }
6166
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006167 // load (select (cond, null, P)) -> load P
6168 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6169 if (C->isNullValue()) {
6170 LI.setOperand(0, SI->getOperand(2));
6171 return &LI;
6172 }
6173
6174 // load (select (cond, P, null)) -> load P
6175 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6176 if (C->isNullValue()) {
6177 LI.setOperand(0, SI->getOperand(1));
6178 return &LI;
6179 }
6180
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006181 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6182 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006183 bool Safe = PN->getParent() == LI.getParent();
6184
6185 // Scan all of the instructions between the PHI and the load to make
6186 // sure there are no instructions that might possibly alter the value
6187 // loaded from the PHI.
6188 if (Safe) {
6189 BasicBlock::iterator I = &LI;
6190 for (--I; !isa<PHINode>(I); --I)
6191 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6192 Safe = false;
6193 break;
6194 }
6195 }
6196
6197 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006198 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006199 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006200 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006201
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006202 if (Safe) {
6203 // Create the PHI.
6204 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6205 InsertNewInstBefore(NewPN, *PN);
6206 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6207
6208 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6209 BasicBlock *BB = PN->getIncomingBlock(i);
6210 Value *&TheLoad = LoadMap[BB];
6211 if (TheLoad == 0) {
6212 Value *InVal = PN->getIncomingValue(i);
6213 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6214 InVal->getName()+".val"),
6215 *BB->getTerminator());
6216 }
6217 NewPN->addIncoming(TheLoad, BB);
6218 }
6219 return ReplaceInstUsesWith(LI, NewPN);
6220 }
6221 }
6222 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006223 return 0;
6224}
6225
Chris Lattner72684fe2005-01-31 05:51:45 +00006226/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6227/// when possible.
6228static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6229 User *CI = cast<User>(SI.getOperand(1));
6230 Value *CastOp = CI->getOperand(0);
6231
6232 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6233 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6234 const Type *SrcPTy = SrcTy->getElementType();
6235
6236 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6237 // If the source is an array, the code below will not succeed. Check to
6238 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6239 // constants.
6240 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6241 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6242 if (ASrcTy->getNumElements() != 0) {
6243 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6244 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6245 SrcTy = cast<PointerType>(CastOp->getType());
6246 SrcPTy = SrcTy->getElementType();
6247 }
6248
6249 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006250 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006251 IC.getTargetData().getTypeSize(DestPTy)) {
6252
6253 // Okay, we are casting from one integer or pointer type to another of
6254 // the same size. Instead of casting the pointer before the store, cast
6255 // the value to be stored.
6256 Value *NewCast;
6257 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6258 NewCast = ConstantExpr::getCast(C, SrcPTy);
6259 else
6260 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6261 SrcPTy,
6262 SI.getOperand(0)->getName()+".c"), SI);
6263
6264 return new StoreInst(NewCast, CastOp);
6265 }
6266 }
6267 }
6268 return 0;
6269}
6270
Chris Lattner31f486c2005-01-31 05:36:43 +00006271Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6272 Value *Val = SI.getOperand(0);
6273 Value *Ptr = SI.getOperand(1);
6274
6275 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006276 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006277 ++NumCombined;
6278 return 0;
6279 }
6280
Chris Lattner5997cf92006-02-08 03:25:32 +00006281 // Do really simple DSE, to catch cases where there are several consequtive
6282 // stores to the same location, separated by a few arithmetic operations. This
6283 // situation often occurs with bitfield accesses.
6284 BasicBlock::iterator BBI = &SI;
6285 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6286 --ScanInsts) {
6287 --BBI;
6288
6289 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6290 // Prev store isn't volatile, and stores to the same location?
6291 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6292 ++NumDeadStore;
6293 ++BBI;
6294 EraseInstFromFunction(*PrevSI);
6295 continue;
6296 }
6297 break;
6298 }
6299
6300 // Don't skip over loads or things that can modify memory.
6301 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6302 break;
6303 }
6304
6305
6306 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006307
6308 // store X, null -> turns into 'unreachable' in SimplifyCFG
6309 if (isa<ConstantPointerNull>(Ptr)) {
6310 if (!isa<UndefValue>(Val)) {
6311 SI.setOperand(0, UndefValue::get(Val->getType()));
6312 if (Instruction *U = dyn_cast<Instruction>(Val))
6313 WorkList.push_back(U); // Dropped a use.
6314 ++NumCombined;
6315 }
6316 return 0; // Do not modify these!
6317 }
6318
6319 // store undef, Ptr -> noop
6320 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006321 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006322 ++NumCombined;
6323 return 0;
6324 }
6325
Chris Lattner72684fe2005-01-31 05:51:45 +00006326 // If the pointer destination is a cast, see if we can fold the cast into the
6327 // source instead.
6328 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6329 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6330 return Res;
6331 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6332 if (CE->getOpcode() == Instruction::Cast)
6333 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6334 return Res;
6335
Chris Lattner219175c2005-09-12 23:23:25 +00006336
6337 // If this store is the last instruction in the basic block, and if the block
6338 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006339 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006340 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6341 if (BI->isUnconditional()) {
6342 // Check to see if the successor block has exactly two incoming edges. If
6343 // so, see if the other predecessor contains a store to the same location.
6344 // if so, insert a PHI node (if needed) and move the stores down.
6345 BasicBlock *Dest = BI->getSuccessor(0);
6346
6347 pred_iterator PI = pred_begin(Dest);
6348 BasicBlock *Other = 0;
6349 if (*PI != BI->getParent())
6350 Other = *PI;
6351 ++PI;
6352 if (PI != pred_end(Dest)) {
6353 if (*PI != BI->getParent())
6354 if (Other)
6355 Other = 0;
6356 else
6357 Other = *PI;
6358 if (++PI != pred_end(Dest))
6359 Other = 0;
6360 }
6361 if (Other) { // If only one other pred...
6362 BBI = Other->getTerminator();
6363 // Make sure this other block ends in an unconditional branch and that
6364 // there is an instruction before the branch.
6365 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6366 BBI != Other->begin()) {
6367 --BBI;
6368 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6369
6370 // If this instruction is a store to the same location.
6371 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6372 // Okay, we know we can perform this transformation. Insert a PHI
6373 // node now if we need it.
6374 Value *MergedVal = OtherStore->getOperand(0);
6375 if (MergedVal != SI.getOperand(0)) {
6376 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6377 PN->reserveOperandSpace(2);
6378 PN->addIncoming(SI.getOperand(0), SI.getParent());
6379 PN->addIncoming(OtherStore->getOperand(0), Other);
6380 MergedVal = InsertNewInstBefore(PN, Dest->front());
6381 }
6382
6383 // Advance to a place where it is safe to insert the new store and
6384 // insert it.
6385 BBI = Dest->begin();
6386 while (isa<PHINode>(BBI)) ++BBI;
6387 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6388 OtherStore->isVolatile()), *BBI);
6389
6390 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006391 EraseInstFromFunction(SI);
6392 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006393 ++NumCombined;
6394 return 0;
6395 }
6396 }
6397 }
6398 }
6399
Chris Lattner31f486c2005-01-31 05:36:43 +00006400 return 0;
6401}
6402
6403
Chris Lattner9eef8a72003-06-04 04:46:00 +00006404Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6405 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006406 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006407 BasicBlock *TrueDest;
6408 BasicBlock *FalseDest;
6409 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6410 !isa<Constant>(X)) {
6411 // Swap Destinations and condition...
6412 BI.setCondition(X);
6413 BI.setSuccessor(0, FalseDest);
6414 BI.setSuccessor(1, TrueDest);
6415 return &BI;
6416 }
6417
6418 // Cannonicalize setne -> seteq
6419 Instruction::BinaryOps Op; Value *Y;
6420 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6421 TrueDest, FalseDest)))
6422 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6423 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6424 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6425 std::string Name = I->getName(); I->setName("");
6426 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6427 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006428 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006429 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006430 BI.setSuccessor(0, FalseDest);
6431 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006432 removeFromWorkList(I);
6433 I->getParent()->getInstList().erase(I);
6434 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006435 return &BI;
6436 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006437
Chris Lattner9eef8a72003-06-04 04:46:00 +00006438 return 0;
6439}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006440
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006441Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6442 Value *Cond = SI.getCondition();
6443 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6444 if (I->getOpcode() == Instruction::Add)
6445 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6446 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6447 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006448 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006449 AddRHS));
6450 SI.setOperand(0, I->getOperand(0));
6451 WorkList.push_back(I);
6452 return &SI;
6453 }
6454 }
6455 return 0;
6456}
6457
Robert Bocchinoa8352962006-01-13 22:48:06 +00006458Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6459 if (ConstantAggregateZero *C =
6460 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6461 // If packed val is constant 0, replace extract with scalar 0
6462 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6463 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6464 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6465 }
6466 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6467 // If packed val is constant with uniform operands, replace EI
6468 // with that operand
6469 Constant *op0 = cast<Constant>(C->getOperand(0));
6470 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6471 if (C->getOperand(i) != op0) return 0;
6472 return ReplaceInstUsesWith(EI, op0);
6473 }
6474 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6475 if (I->hasOneUse()) {
6476 // Push extractelement into predecessor operation if legal and
6477 // profitable to do so
6478 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6479 if (!isa<Constant>(BO->getOperand(0)) &&
6480 !isa<Constant>(BO->getOperand(1)))
6481 return 0;
6482 ExtractElementInst *newEI0 =
6483 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6484 EI.getName());
6485 ExtractElementInst *newEI1 =
6486 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6487 EI.getName());
6488 InsertNewInstBefore(newEI0, EI);
6489 InsertNewInstBefore(newEI1, EI);
6490 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6491 }
6492 switch(I->getOpcode()) {
6493 case Instruction::Load: {
6494 Value *Ptr = InsertCastBefore(I->getOperand(0),
6495 PointerType::get(EI.getType()), EI);
6496 GetElementPtrInst *GEP =
6497 new GetElementPtrInst(Ptr, EI.getOperand(1),
6498 I->getName() + ".gep");
6499 InsertNewInstBefore(GEP, EI);
6500 return new LoadInst(GEP);
6501 }
6502 default:
6503 return 0;
6504 }
6505 }
6506 return 0;
6507}
6508
6509
Chris Lattner99f48c62002-09-02 04:59:56 +00006510void InstCombiner::removeFromWorkList(Instruction *I) {
6511 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6512 WorkList.end());
6513}
6514
Chris Lattner39c98bb2004-12-08 23:43:58 +00006515
6516/// TryToSinkInstruction - Try to move the specified instruction from its
6517/// current block into the beginning of DestBlock, which can only happen if it's
6518/// safe to move the instruction past all of the instructions between it and the
6519/// end of its block.
6520static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6521 assert(I->hasOneUse() && "Invariants didn't hold!");
6522
Chris Lattnerc4f67e62005-10-27 17:13:11 +00006523 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6524 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006525
Chris Lattner39c98bb2004-12-08 23:43:58 +00006526 // Do not sink alloca instructions out of the entry block.
6527 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6528 return false;
6529
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006530 // We can only sink load instructions if there is nothing between the load and
6531 // the end of block that could change the value.
6532 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006533 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6534 Scan != E; ++Scan)
6535 if (Scan->mayWriteToMemory())
6536 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006537 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00006538
6539 BasicBlock::iterator InsertPos = DestBlock->begin();
6540 while (isa<PHINode>(InsertPos)) ++InsertPos;
6541
Chris Lattner9f269e42005-08-08 19:11:57 +00006542 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00006543 ++NumSunkInst;
6544 return true;
6545}
6546
Chris Lattner113f4f42002-06-25 16:13:24 +00006547bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00006548 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006549 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00006550
Chris Lattner4ed40f72005-07-07 20:40:38 +00006551 {
6552 // Populate the worklist with the reachable instructions.
6553 std::set<BasicBlock*> Visited;
6554 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6555 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6556 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6557 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006558
Chris Lattner4ed40f72005-07-07 20:40:38 +00006559 // Do a quick scan over the function. If we find any blocks that are
6560 // unreachable, remove any instructions inside of them. This prevents
6561 // the instcombine code from having to deal with some bad special cases.
6562 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6563 if (!Visited.count(BB)) {
6564 Instruction *Term = BB->getTerminator();
6565 while (Term != BB->begin()) { // Remove instrs bottom-up
6566 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00006567
Chris Lattner4ed40f72005-07-07 20:40:38 +00006568 DEBUG(std::cerr << "IC: DCE: " << *I);
6569 ++NumDeadInst;
6570
6571 if (!I->use_empty())
6572 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6573 I->eraseFromParent();
6574 }
6575 }
6576 }
Chris Lattnerca081252001-12-14 16:52:21 +00006577
6578 while (!WorkList.empty()) {
6579 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6580 WorkList.pop_back();
6581
Misha Brukman632df282002-10-29 23:06:16 +00006582 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00006583 // Check to see if we can DIE the instruction...
6584 if (isInstructionTriviallyDead(I)) {
6585 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006586 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00006587 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00006588 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006589
Chris Lattnercd517ff2005-01-28 19:32:01 +00006590 DEBUG(std::cerr << "IC: DCE: " << *I);
6591
6592 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006593 removeFromWorkList(I);
6594 continue;
6595 }
Chris Lattner99f48c62002-09-02 04:59:56 +00006596
Misha Brukman632df282002-10-29 23:06:16 +00006597 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00006598 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006599 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00006600 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006601 cast<Constant>(Ptr)->isNullValue() &&
6602 !isa<ConstantPointerNull>(C) &&
6603 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00006604 // If this is a constant expr gep that is effectively computing an
6605 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6606 bool isFoldableGEP = true;
6607 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6608 if (!isa<ConstantInt>(I->getOperand(i)))
6609 isFoldableGEP = false;
6610 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006611 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00006612 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6613 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00006614 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00006615 C = ConstantExpr::getCast(C, I->getType());
6616 }
6617 }
6618
Chris Lattnercd517ff2005-01-28 19:32:01 +00006619 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6620
Chris Lattner99f48c62002-09-02 04:59:56 +00006621 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00006622 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00006623 ReplaceInstUsesWith(*I, C);
6624
Chris Lattner99f48c62002-09-02 04:59:56 +00006625 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006626 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00006627 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006628 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00006629 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006630
Chris Lattner39c98bb2004-12-08 23:43:58 +00006631 // See if we can trivially sink this instruction to a successor basic block.
6632 if (I->hasOneUse()) {
6633 BasicBlock *BB = I->getParent();
6634 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6635 if (UserParent != BB) {
6636 bool UserIsSuccessor = false;
6637 // See if the user is one of our successors.
6638 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6639 if (*SI == UserParent) {
6640 UserIsSuccessor = true;
6641 break;
6642 }
6643
6644 // If the user is one of our immediate successors, and if that successor
6645 // only has us as a predecessors (we'd have to split the critical edge
6646 // otherwise), we can keep going.
6647 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6648 next(pred_begin(UserParent)) == pred_end(UserParent))
6649 // Okay, the CFG is simple enough, try to sink this instruction.
6650 Changed |= TryToSinkInstruction(I, UserParent);
6651 }
6652 }
6653
Chris Lattnerca081252001-12-14 16:52:21 +00006654 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006655 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00006656 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00006657 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00006658 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006659 DEBUG(std::cerr << "IC: Old = " << *I
6660 << " New = " << *Result);
6661
Chris Lattner396dbfe2004-06-09 05:08:07 +00006662 // Everything uses the new instruction now.
6663 I->replaceAllUsesWith(Result);
6664
6665 // Push the new instruction and any users onto the worklist.
6666 WorkList.push_back(Result);
6667 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006668
6669 // Move the name to the new instruction first...
6670 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006671 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006672
6673 // Insert the new instruction into the basic block...
6674 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006675 BasicBlock::iterator InsertPos = I;
6676
6677 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6678 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6679 ++InsertPos;
6680
6681 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006682
Chris Lattner63d75af2004-05-01 23:27:23 +00006683 // Make sure that we reprocess all operands now that we reduced their
6684 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006685 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6686 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6687 WorkList.push_back(OpI);
6688
Chris Lattner396dbfe2004-06-09 05:08:07 +00006689 // Instructions can end up on the worklist more than once. Make sure
6690 // we do not process an instruction that has been deleted.
6691 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006692
6693 // Erase the old instruction.
6694 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006695 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006696 DEBUG(std::cerr << "IC: MOD = " << *I);
6697
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006698 // If the instruction was modified, it's possible that it is now dead.
6699 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006700 if (isInstructionTriviallyDead(I)) {
6701 // Make sure we process all operands now that we are reducing their
6702 // use counts.
6703 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6704 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6705 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006706
Chris Lattner63d75af2004-05-01 23:27:23 +00006707 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00006708 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006709 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006710 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006711 } else {
6712 WorkList.push_back(Result);
6713 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006714 }
Chris Lattner053c0932002-05-14 15:24:07 +00006715 }
Chris Lattner260ab202002-04-18 17:39:14 +00006716 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006717 }
6718 }
6719
Chris Lattner260ab202002-04-18 17:39:14 +00006720 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006721}
6722
Brian Gaeke38b79e82004-07-27 17:43:21 +00006723FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006724 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006725}
Brian Gaeke960707c2003-11-11 22:41:34 +00006726