blob: 80444028d2e3877c1b4507acef4fa3cd712d2cf0 [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'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000760 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000761 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000762 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000763 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));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000770 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.
Chris Lattner7d852282006-02-13 22:41:07 +0000892 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
893 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
894
895 // If any of the sign extended bits are demanded, we know that the sign
896 // bit is demanded.
897 if (NewBits & DemandedMask)
898 InputDemandedBits |= InSignBit;
899
900 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000901 KnownZero, KnownOne, Depth+1))
902 return true;
903 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
904
905 // If the sign bit of the input is known set or clear, then we know the
906 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +0000907
Chris Lattner0157e7f2006-02-11 09:31:47 +0000908 // If the input sign bit is known zero, or if the NewBits are not demanded
909 // convert this into a zero extension.
910 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +0000911 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +0000912 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +0000913 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +0000914 I->getOperand(0)->getName());
915 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000916 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +0000917 NewVal = new CastInst(NewVal, I->getType(), I->getName());
918 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +0000919 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000920 } else if (KnownOne & InSignBit) { // Input sign bit known set
921 KnownOne |= NewBits;
922 KnownZero &= ~NewBits;
923 } else { // Input sign bit unknown
924 KnownZero &= ~NewBits;
925 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +0000926 }
Chris Lattner2590e512006-02-07 06:56:34 +0000927 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000928 break;
Chris Lattner2590e512006-02-07 06:56:34 +0000929 }
Chris Lattner2590e512006-02-07 06:56:34 +0000930 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000931 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
932 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
933 KnownZero, KnownOne, Depth+1))
934 return true;
935 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
936 KnownZero <<= SA->getValue();
937 KnownOne <<= SA->getValue();
938 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
939 }
Chris Lattner2590e512006-02-07 06:56:34 +0000940 break;
941 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000942 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
943 unsigned ShAmt = SA->getValue();
944
945 // Compute the new bits that are at the top now.
946 uint64_t HighBits = (1ULL << ShAmt)-1;
947 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +0000948 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +0000949 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000950 if (SimplifyDemandedBits(I->getOperand(0),
951 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000952 KnownZero, KnownOne, Depth+1))
953 return true;
954 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000955 KnownZero &= TypeMask;
956 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000957 KnownZero >>= ShAmt;
958 KnownOne >>= ShAmt;
959 KnownZero |= HighBits; // high bits known zero.
960 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +0000961 if (SimplifyDemandedBits(I->getOperand(0),
962 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000963 KnownZero, KnownOne, Depth+1))
964 return true;
965 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +0000966 KnownZero &= TypeMask;
967 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000968 KnownZero >>= SA->getValue();
969 KnownOne >>= SA->getValue();
970
971 // Handle the sign bits.
972 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
973 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
974
975 // If the input sign bit is known to be zero, or if none of the top bits
976 // are demanded, turn this into an unsigned shift right.
977 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
978 // Convert the input to unsigned.
979 Instruction *NewVal;
980 NewVal = new CastInst(I->getOperand(0),
981 I->getType()->getUnsignedVersion(),
982 I->getOperand(0)->getName());
983 InsertNewInstBefore(NewVal, *I);
984 // Perform the unsigned shift right.
985 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
986 InsertNewInstBefore(NewVal, *I);
987 // Then cast that to the destination type.
988 NewVal = new CastInst(NewVal, I->getType(), I->getName());
989 InsertNewInstBefore(NewVal, *I);
990 return UpdateValueUsesWith(I, NewVal);
991 } else if (KnownOne & SignBit) { // New bits are known one.
992 KnownOne |= HighBits;
993 }
Chris Lattner2590e512006-02-07 06:56:34 +0000994 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000995 }
Chris Lattner2590e512006-02-07 06:56:34 +0000996 break;
997 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000998
999 // If the client is only demanding bits that we know, return the known
1000 // constant.
1001 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1002 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001003 return false;
1004}
1005
Chris Lattner623826c2004-09-28 21:48:02 +00001006// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1007// true when both operands are equal...
1008//
1009static bool isTrueWhenEqual(Instruction &I) {
1010 return I.getOpcode() == Instruction::SetEQ ||
1011 I.getOpcode() == Instruction::SetGE ||
1012 I.getOpcode() == Instruction::SetLE;
1013}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001014
1015/// AssociativeOpt - Perform an optimization on an associative operator. This
1016/// function is designed to check a chain of associative operators for a
1017/// potential to apply a certain optimization. Since the optimization may be
1018/// applicable if the expression was reassociated, this checks the chain, then
1019/// reassociates the expression as necessary to expose the optimization
1020/// opportunity. This makes use of a special Functor, which must define
1021/// 'shouldApply' and 'apply' methods.
1022///
1023template<typename Functor>
1024Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1025 unsigned Opcode = Root.getOpcode();
1026 Value *LHS = Root.getOperand(0);
1027
1028 // Quick check, see if the immediate LHS matches...
1029 if (F.shouldApply(LHS))
1030 return F.apply(Root);
1031
1032 // Otherwise, if the LHS is not of the same opcode as the root, return.
1033 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001034 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001035 // Should we apply this transform to the RHS?
1036 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1037
1038 // If not to the RHS, check to see if we should apply to the LHS...
1039 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1040 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1041 ShouldApply = true;
1042 }
1043
1044 // If the functor wants to apply the optimization to the RHS of LHSI,
1045 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1046 if (ShouldApply) {
1047 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001048
Chris Lattnerb8b97502003-08-13 19:01:45 +00001049 // Now all of the instructions are in the current basic block, go ahead
1050 // and perform the reassociation.
1051 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1052
1053 // First move the selected RHS to the LHS of the root...
1054 Root.setOperand(0, LHSI->getOperand(1));
1055
1056 // Make what used to be the LHS of the root be the user of the root...
1057 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001058 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001059 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1060 return 0;
1061 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001062 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001063 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001064 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1065 BasicBlock::iterator ARI = &Root; ++ARI;
1066 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1067 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001068
1069 // Now propagate the ExtraOperand down the chain of instructions until we
1070 // get to LHSI.
1071 while (TmpLHSI != LHSI) {
1072 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001073 // Move the instruction to immediately before the chain we are
1074 // constructing to avoid breaking dominance properties.
1075 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1076 BB->getInstList().insert(ARI, NextLHSI);
1077 ARI = NextLHSI;
1078
Chris Lattnerb8b97502003-08-13 19:01:45 +00001079 Value *NextOp = NextLHSI->getOperand(1);
1080 NextLHSI->setOperand(1, ExtraOperand);
1081 TmpLHSI = NextLHSI;
1082 ExtraOperand = NextOp;
1083 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001084
Chris Lattnerb8b97502003-08-13 19:01:45 +00001085 // Now that the instructions are reassociated, have the functor perform
1086 // the transformation...
1087 return F.apply(Root);
1088 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001089
Chris Lattnerb8b97502003-08-13 19:01:45 +00001090 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1091 }
1092 return 0;
1093}
1094
1095
1096// AddRHS - Implements: X + X --> X << 1
1097struct AddRHS {
1098 Value *RHS;
1099 AddRHS(Value *rhs) : RHS(rhs) {}
1100 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1101 Instruction *apply(BinaryOperator &Add) const {
1102 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1103 ConstantInt::get(Type::UByteTy, 1));
1104 }
1105};
1106
1107// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1108// iff C1&C2 == 0
1109struct AddMaskingAnd {
1110 Constant *C2;
1111 AddMaskingAnd(Constant *c) : C2(c) {}
1112 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001113 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001114 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001115 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001116 }
1117 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001118 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001119 }
1120};
1121
Chris Lattner86102b82005-01-01 16:22:27 +00001122static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001123 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001124 if (isa<CastInst>(I)) {
1125 if (Constant *SOC = dyn_cast<Constant>(SO))
1126 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001127
Chris Lattner86102b82005-01-01 16:22:27 +00001128 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1129 SO->getName() + ".cast"), I);
1130 }
1131
Chris Lattner183b3362004-04-09 19:05:30 +00001132 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001133 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1134 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001135
Chris Lattner183b3362004-04-09 19:05:30 +00001136 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1137 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001138 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1139 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001140 }
1141
1142 Value *Op0 = SO, *Op1 = ConstOperand;
1143 if (!ConstIsRHS)
1144 std::swap(Op0, Op1);
1145 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001146 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1147 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1148 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1149 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001150 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001151 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001152 abort();
1153 }
Chris Lattner86102b82005-01-01 16:22:27 +00001154 return IC->InsertNewInstBefore(New, I);
1155}
1156
1157// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1158// constant as the other operand, try to fold the binary operator into the
1159// select arguments. This also works for Cast instructions, which obviously do
1160// not have a second operand.
1161static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1162 InstCombiner *IC) {
1163 // Don't modify shared select instructions
1164 if (!SI->hasOneUse()) return 0;
1165 Value *TV = SI->getOperand(1);
1166 Value *FV = SI->getOperand(2);
1167
1168 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001169 // Bool selects with constant operands can be folded to logical ops.
1170 if (SI->getType() == Type::BoolTy) return 0;
1171
Chris Lattner86102b82005-01-01 16:22:27 +00001172 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1173 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1174
1175 return new SelectInst(SI->getCondition(), SelectTrueVal,
1176 SelectFalseVal);
1177 }
1178 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001179}
1180
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001181
1182/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1183/// node as operand #0, see if we can fold the instruction into the PHI (which
1184/// is only possible if all operands to the PHI are constants).
1185Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1186 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001187 unsigned NumPHIValues = PN->getNumIncomingValues();
1188 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1189 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001190
1191 // Check to see if all of the operands of the PHI are constants. If not, we
1192 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001193 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001194 if (!isa<Constant>(PN->getIncomingValue(i)))
1195 return 0;
1196
1197 // Okay, we can do the transformation: create the new PHI node.
1198 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1199 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001200 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001201 InsertNewInstBefore(NewPN, *PN);
1202
1203 // Next, add all of the operands to the PHI.
1204 if (I.getNumOperands() == 2) {
1205 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001206 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001207 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1208 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1209 PN->getIncomingBlock(i));
1210 }
1211 } else {
1212 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1213 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001214 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001215 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1216 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1217 PN->getIncomingBlock(i));
1218 }
1219 }
1220 return ReplaceInstUsesWith(I, NewPN);
1221}
1222
Chris Lattner113f4f42002-06-25 16:13:24 +00001223Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001224 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001225 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001226
Chris Lattnercf4a9962004-04-10 22:01:55 +00001227 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001228 // X + undef -> undef
1229 if (isa<UndefValue>(RHS))
1230 return ReplaceInstUsesWith(I, RHS);
1231
Chris Lattnercf4a9962004-04-10 22:01:55 +00001232 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001233 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1234 if (RHSC->isNullValue())
1235 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001236 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1237 if (CFP->isExactlyValue(-0.0))
1238 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001239 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001240
Chris Lattnercf4a9962004-04-10 22:01:55 +00001241 // X + (signbit) --> X ^ signbit
1242 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001243 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001244 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001245 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001246 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001247
1248 if (isa<PHINode>(LHS))
1249 if (Instruction *NV = FoldOpIntoPhi(I))
1250 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001251
Chris Lattner330628a2006-01-06 17:59:59 +00001252 ConstantInt *XorRHS = 0;
1253 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001254 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1255 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1256 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1257 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1258
1259 uint64_t C0080Val = 1ULL << 31;
1260 int64_t CFF80Val = -C0080Val;
1261 unsigned Size = 32;
1262 do {
1263 if (TySizeBits > Size) {
1264 bool Found = false;
1265 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1266 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1267 if (RHSSExt == CFF80Val) {
1268 if (XorRHS->getZExtValue() == C0080Val)
1269 Found = true;
1270 } else if (RHSZExt == C0080Val) {
1271 if (XorRHS->getSExtValue() == CFF80Val)
1272 Found = true;
1273 }
1274 if (Found) {
1275 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001276 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001277 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001278 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001279 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001280 Size = 0; // Not a sign ext, but can't be any others either.
1281 goto FoundSExt;
1282 }
1283 }
1284 Size >>= 1;
1285 C0080Val >>= Size;
1286 CFF80Val >>= Size;
1287 } while (Size >= 8);
1288
1289FoundSExt:
1290 const Type *MiddleType = 0;
1291 switch (Size) {
1292 default: break;
1293 case 32: MiddleType = Type::IntTy; break;
1294 case 16: MiddleType = Type::ShortTy; break;
1295 case 8: MiddleType = Type::SByteTy; break;
1296 }
1297 if (MiddleType) {
1298 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1299 InsertNewInstBefore(NewTrunc, I);
1300 return new CastInst(NewTrunc, I.getType());
1301 }
1302 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001303 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001304
Chris Lattnerb8b97502003-08-13 19:01:45 +00001305 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001306 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001307 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001308
1309 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1310 if (RHSI->getOpcode() == Instruction::Sub)
1311 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1312 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1313 }
1314 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1315 if (LHSI->getOpcode() == Instruction::Sub)
1316 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1317 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1318 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001319 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001320
Chris Lattner147e9752002-05-08 22:46:53 +00001321 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001322 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001323 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001324
1325 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001326 if (!isa<Constant>(RHS))
1327 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001328 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001329
Misha Brukmanb1c93172005-04-21 23:48:37 +00001330
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001331 ConstantInt *C2;
1332 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1333 if (X == RHS) // X*C + X --> X * (C+1)
1334 return BinaryOperator::createMul(RHS, AddOne(C2));
1335
1336 // X*C1 + X*C2 --> X * (C1+C2)
1337 ConstantInt *C1;
1338 if (X == dyn_castFoldableMul(RHS, C1))
1339 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001340 }
1341
1342 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001343 if (dyn_castFoldableMul(RHS, C2) == LHS)
1344 return BinaryOperator::createMul(LHS, AddOne(C2));
1345
Chris Lattner57c8d992003-02-18 19:57:07 +00001346
Chris Lattnerb8b97502003-08-13 19:01:45 +00001347 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001348 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001349 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001350
Chris Lattnerb9cde762003-10-02 15:11:26 +00001351 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001352 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001353 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1354 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1355 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001356 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001357
Chris Lattnerbff91d92004-10-08 05:07:56 +00001358 // (X & FF00) + xx00 -> (X+xx00) & FF00
1359 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1360 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1361 if (Anded == CRHS) {
1362 // See if all bits from the first bit set in the Add RHS up are included
1363 // in the mask. First, get the rightmost bit.
1364 uint64_t AddRHSV = CRHS->getRawValue();
1365
1366 // Form a mask of all bits from the lowest bit added through the top.
1367 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001368 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001369
1370 // See if the and mask includes all of these bits.
1371 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001372
Chris Lattnerbff91d92004-10-08 05:07:56 +00001373 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1374 // Okay, the xform is safe. Insert the new add pronto.
1375 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1376 LHS->getName()), I);
1377 return BinaryOperator::createAnd(NewAdd, C2);
1378 }
1379 }
1380 }
1381
Chris Lattnerd4252a72004-07-30 07:50:03 +00001382 // Try to fold constant add into select arguments.
1383 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001384 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001385 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001386 }
1387
Chris Lattner113f4f42002-06-25 16:13:24 +00001388 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001389}
1390
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001391// isSignBit - Return true if the value represented by the constant only has the
1392// highest order bit set.
1393static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001394 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001395 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001396}
1397
Chris Lattner022167f2004-03-13 00:11:49 +00001398/// RemoveNoopCast - Strip off nonconverting casts from the value.
1399///
1400static Value *RemoveNoopCast(Value *V) {
1401 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1402 const Type *CTy = CI->getType();
1403 const Type *OpTy = CI->getOperand(0)->getType();
1404 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001405 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001406 return RemoveNoopCast(CI->getOperand(0));
1407 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1408 return RemoveNoopCast(CI->getOperand(0));
1409 }
1410 return V;
1411}
1412
Chris Lattner113f4f42002-06-25 16:13:24 +00001413Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001415
Chris Lattnere6794492002-08-12 21:17:25 +00001416 if (Op0 == Op1) // sub X, X -> 0
1417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001418
Chris Lattnere6794492002-08-12 21:17:25 +00001419 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001420 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001421 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001422
Chris Lattner81a7a232004-10-16 18:11:37 +00001423 if (isa<UndefValue>(Op0))
1424 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1425 if (isa<UndefValue>(Op1))
1426 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1427
Chris Lattner8f2f5982003-11-05 01:06:05 +00001428 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1429 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001430 if (C->isAllOnesValue())
1431 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001432
Chris Lattner8f2f5982003-11-05 01:06:05 +00001433 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001434 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001435 if (match(Op1, m_Not(m_Value(X))))
1436 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001437 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001438 // -((uint)X >> 31) -> ((int)X >> 31)
1439 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001440 if (C->isNullValue()) {
1441 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1442 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001443 if (SI->getOpcode() == Instruction::Shr)
1444 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1445 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001446 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001447 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001448 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001449 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001450 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001451 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001452 // Ok, the transformation is safe. Insert a cast of the incoming
1453 // value, then the new shift, then the new cast.
1454 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1455 SI->getOperand(0)->getName());
1456 Value *InV = InsertNewInstBefore(FirstCast, I);
1457 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1458 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001459 if (NewShift->getType() == I.getType())
1460 return NewShift;
1461 else {
1462 InV = InsertNewInstBefore(NewShift, I);
1463 return new CastInst(NewShift, I.getType());
1464 }
Chris Lattner92295c52004-03-12 23:53:13 +00001465 }
1466 }
Chris Lattner022167f2004-03-13 00:11:49 +00001467 }
Chris Lattner183b3362004-04-09 19:05:30 +00001468
1469 // Try to fold constant sub into select arguments.
1470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001471 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001472 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001473
1474 if (isa<PHINode>(Op0))
1475 if (Instruction *NV = FoldOpIntoPhi(I))
1476 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001477 }
1478
Chris Lattnera9be4492005-04-07 16:15:25 +00001479 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1480 if (Op1I->getOpcode() == Instruction::Add &&
1481 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001482 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001483 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001484 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001485 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001486 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1487 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1488 // C1-(X+C2) --> (C1-C2)-X
1489 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1490 Op1I->getOperand(0));
1491 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001492 }
1493
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001494 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1496 // is not used by anyone else...
1497 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001498 if (Op1I->getOpcode() == Instruction::Sub &&
1499 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001500 // Swap the two operands of the subexpr...
1501 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1502 Op1I->setOperand(0, IIOp1);
1503 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001504
Chris Lattner3082c5a2003-02-18 19:28:33 +00001505 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001506 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001507 }
1508
1509 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1510 //
1511 if (Op1I->getOpcode() == Instruction::And &&
1512 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1513 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1514
Chris Lattner396dbfe2004-06-09 05:08:07 +00001515 Value *NewNot =
1516 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001517 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001518 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001519
Chris Lattner0aee4b72004-10-06 15:08:25 +00001520 // -(X sdiv C) -> (X sdiv -C)
1521 if (Op1I->getOpcode() == Instruction::Div)
1522 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001523 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001524 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001525 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001526 ConstantExpr::getNeg(DivRHS));
1527
Chris Lattner57c8d992003-02-18 19:57:07 +00001528 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001529 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001530 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001531 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001532 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001533 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001534 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001535 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001536 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001537
Chris Lattner47060462005-04-07 17:14:51 +00001538 if (!Op0->getType()->isFloatingPoint())
1539 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1540 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001541 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1542 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1543 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1544 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001545 } else if (Op0I->getOpcode() == Instruction::Sub) {
1546 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1547 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001548 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001549
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001550 ConstantInt *C1;
1551 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1552 if (X == Op1) { // X*C - X --> X * (C-1)
1553 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1554 return BinaryOperator::createMul(Op1, CP1);
1555 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001556
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001557 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1558 if (X == dyn_castFoldableMul(Op1, C2))
1559 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1560 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001561 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001562}
1563
Chris Lattnere79e8542004-02-23 06:38:22 +00001564/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1565/// really just returns true if the most significant (sign) bit is set.
1566static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1567 if (RHS->getType()->isSigned()) {
1568 // True if source is LHS < 0 or LHS <= -1
1569 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1570 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1571 } else {
1572 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1573 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1574 // the size of the integer type.
1575 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001576 return RHSC->getValue() ==
1577 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001578 if (Opcode == Instruction::SetGT)
1579 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001580 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001581 }
1582 return false;
1583}
1584
Chris Lattner113f4f42002-06-25 16:13:24 +00001585Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001586 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001587 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001588
Chris Lattner81a7a232004-10-16 18:11:37 +00001589 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1590 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1591
Chris Lattnere6794492002-08-12 21:17:25 +00001592 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001593 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001595
1596 // ((X << C1)*C2) == (X * (C2 << C1))
1597 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1598 if (SI->getOpcode() == Instruction::Shl)
1599 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001600 return BinaryOperator::createMul(SI->getOperand(0),
1601 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001602
Chris Lattnercce81be2003-09-11 22:24:54 +00001603 if (CI->isNullValue())
1604 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1605 if (CI->equalsInt(1)) // X * 1 == X
1606 return ReplaceInstUsesWith(I, Op0);
1607 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001608 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001609
Chris Lattnercce81be2003-09-11 22:24:54 +00001610 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001611 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1612 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001613 return new ShiftInst(Instruction::Shl, Op0,
1614 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001615 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001616 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001617 if (Op1F->isNullValue())
1618 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001619
Chris Lattner3082c5a2003-02-18 19:28:33 +00001620 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1621 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1622 if (Op1F->getValue() == 1.0)
1623 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1624 }
Chris Lattner183b3362004-04-09 19:05:30 +00001625
1626 // Try to fold constant mul into select arguments.
1627 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001628 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001629 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001630
1631 if (isa<PHINode>(Op0))
1632 if (Instruction *NV = FoldOpIntoPhi(I))
1633 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001634 }
1635
Chris Lattner934a64cf2003-03-10 23:23:04 +00001636 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1637 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001638 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001639
Chris Lattner2635b522004-02-23 05:39:21 +00001640 // If one of the operands of the multiply is a cast from a boolean value, then
1641 // we know the bool is either zero or one, so this is a 'masking' multiply.
1642 // See if we can simplify things based on how the boolean was originally
1643 // formed.
1644 CastInst *BoolCast = 0;
1645 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1646 if (CI->getOperand(0)->getType() == Type::BoolTy)
1647 BoolCast = CI;
1648 if (!BoolCast)
1649 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1650 if (CI->getOperand(0)->getType() == Type::BoolTy)
1651 BoolCast = CI;
1652 if (BoolCast) {
1653 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1654 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1655 const Type *SCOpTy = SCIOp0->getType();
1656
Chris Lattnere79e8542004-02-23 06:38:22 +00001657 // If the setcc is true iff the sign bit of X is set, then convert this
1658 // multiply into a shift/and combination.
1659 if (isa<ConstantInt>(SCIOp1) &&
1660 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001661 // Shift the X value right to turn it into "all signbits".
1662 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001663 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001664 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001665 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001666 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1667 SCIOp0->getName()), I);
1668 }
1669
1670 Value *V =
1671 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1672 BoolCast->getOperand(0)->getName()+
1673 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001674
1675 // If the multiply type is not the same as the source type, sign extend
1676 // or truncate to the multiply type.
1677 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001678 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001679
Chris Lattner2635b522004-02-23 05:39:21 +00001680 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001681 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001682 }
1683 }
1684 }
1685
Chris Lattner113f4f42002-06-25 16:13:24 +00001686 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001687}
1688
Chris Lattner113f4f42002-06-25 16:13:24 +00001689Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001690 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001691
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001692 if (isa<UndefValue>(Op0)) // undef / X -> 0
1693 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1694 if (isa<UndefValue>(Op1))
1695 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1696
1697 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001698 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001699 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001700 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001701
Chris Lattnere20c3342004-04-26 14:01:59 +00001702 // div X, -1 == -X
1703 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001704 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001705
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001706 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001707 if (LHS->getOpcode() == Instruction::Div)
1708 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001709 // (X / C1) / C2 -> X / (C1*C2)
1710 return BinaryOperator::createDiv(LHS->getOperand(0),
1711 ConstantExpr::getMul(RHS, LHSRHS));
1712 }
1713
Chris Lattner3082c5a2003-02-18 19:28:33 +00001714 // Check to see if this is an unsigned division with an exact power of 2,
1715 // if so, convert to a right shift.
1716 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1717 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001718 if (isPowerOf2_64(Val)) {
1719 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001720 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001721 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001722 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001723
Chris Lattner4ad08352004-10-09 02:50:40 +00001724 // -X/C -> X/-C
1725 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001726 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001727 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1728
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001729 if (!RHS->isNullValue()) {
1730 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001731 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001732 return R;
1733 if (isa<PHINode>(Op0))
1734 if (Instruction *NV = FoldOpIntoPhi(I))
1735 return NV;
1736 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001737 }
1738
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001739 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1740 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1741 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1742 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1743 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1744 if (STO->getValue() == 0) { // Couldn't be this argument.
1745 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001746 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001747 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001748 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001749 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001750 }
1751
Chris Lattner42362612005-04-08 04:03:26 +00001752 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001753 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1754 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001755 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1756 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1757 TC, SI->getName()+".t");
1758 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001759
Chris Lattner42362612005-04-08 04:03:26 +00001760 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1761 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1762 FC, SI->getName()+".f");
1763 FSI = InsertNewInstBefore(FSI, I);
1764 return new SelectInst(SI->getOperand(0), TSI, FSI);
1765 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001766 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001767
Chris Lattner3082c5a2003-02-18 19:28:33 +00001768 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001769 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001770 if (LHS->equalsInt(0))
1771 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1772
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001773 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001774 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001775 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001776 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1777 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001778 const Type *NTy = Op0->getType()->getUnsignedVersion();
1779 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1780 InsertNewInstBefore(LHS, I);
1781 Value *RHS;
1782 if (Constant *R = dyn_cast<Constant>(Op1))
1783 RHS = ConstantExpr::getCast(R, NTy);
1784 else
1785 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1786 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1787 InsertNewInstBefore(Div, I);
1788 return new CastInst(Div, I.getType());
1789 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001790 } else {
1791 // Known to be an unsigned division.
1792 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1793 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1794 if (RHSI->getOpcode() == Instruction::Shl &&
1795 isa<ConstantUInt>(RHSI->getOperand(0))) {
1796 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1797 if (isPowerOf2_64(C1)) {
1798 unsigned C2 = Log2_64(C1);
1799 Value *Add = RHSI->getOperand(1);
1800 if (C2) {
1801 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1802 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1803 "tmp"), I);
1804 }
1805 return new ShiftInst(Instruction::Shr, Op0, Add);
1806 }
1807 }
1808 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001809 }
1810
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001811 return 0;
1812}
1813
1814
Chris Lattner113f4f42002-06-25 16:13:24 +00001815Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001816 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001817
1818 // 0 % X == 0, we don't need to preserve faults!
1819 if (Constant *LHS = dyn_cast<Constant>(Op0))
1820 if (LHS->isNullValue())
1821 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1822
1823 if (isa<UndefValue>(Op0)) // undef % X -> 0
1824 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1825 if (isa<UndefValue>(Op1))
1826 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1827
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001828 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001829 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001830 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001831 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001832 // X % -Y -> X % Y
1833 AddUsesToWorkList(I);
1834 I.setOperand(1, RHSNeg);
1835 return &I;
1836 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001837
1838 // If the top bits of both operands are zero (i.e. we can prove they are
1839 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001840 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1841 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00001842 const Type *NTy = Op0->getType()->getUnsignedVersion();
1843 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1844 InsertNewInstBefore(LHS, I);
1845 Value *RHS;
1846 if (Constant *R = dyn_cast<Constant>(Op1))
1847 RHS = ConstantExpr::getCast(R, NTy);
1848 else
1849 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1850 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1851 InsertNewInstBefore(Rem, I);
1852 return new CastInst(Rem, I.getType());
1853 }
1854 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00001855
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001856 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001857 // X % 0 == undef, we don't need to preserve faults!
1858 if (RHS->equalsInt(0))
1859 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1860
Chris Lattner3082c5a2003-02-18 19:28:33 +00001861 if (RHS->equalsInt(1)) // X % 1 == 0
1862 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1863
1864 // Check to see if this is an unsigned remainder with an exact power of 2,
1865 // if so, convert to a bitwise and.
1866 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001867 if (isPowerOf2_64(C->getValue()))
1868 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001869
1870 if (!RHS->isNullValue()) {
1871 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001872 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001873 return R;
1874 if (isa<PHINode>(Op0))
1875 if (Instruction *NV = FoldOpIntoPhi(I))
1876 return NV;
1877 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001878 }
1879
Chris Lattner2e90b732006-02-05 07:54:04 +00001880 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1881 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1882 if (I.getType()->isUnsigned() &&
1883 RHSI->getOpcode() == Instruction::Shl &&
1884 isa<ConstantUInt>(RHSI->getOperand(0))) {
1885 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1886 if (isPowerOf2_64(C1)) {
1887 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1888 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1889 "tmp"), I);
1890 return BinaryOperator::createAnd(Op0, Add);
1891 }
1892 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00001893
1894 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1895 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1896 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1897 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1898 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1899 if (STO->getValue() == 0) { // Couldn't be this argument.
1900 I.setOperand(1, SFO);
1901 return &I;
1902 } else if (SFO->getValue() == 0) {
1903 I.setOperand(1, STO);
1904 return &I;
1905 }
1906
1907 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1908 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1909 SubOne(STO), SI->getName()+".t"), I);
1910 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1911 SubOne(SFO), SI->getName()+".f"), I);
1912 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1913 }
1914 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001915 }
1916
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001917 return 0;
1918}
1919
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001920// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001921static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00001922 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1923 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001924
1925 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001926
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001927 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001928 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001929 int64_t Val = INT64_MAX; // All ones
1930 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1931 return CS->getValue() == Val-1;
1932}
1933
1934// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001935static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001936 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1937 return CU->getValue() == 1;
1938
1939 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001940
1941 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001942 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001943 int64_t Val = -1; // All ones
1944 Val <<= TypeBits-1; // Shift over to the right spot
1945 return CS->getValue() == Val+1;
1946}
1947
Chris Lattner35167c32004-06-09 07:59:58 +00001948// isOneBitSet - Return true if there is exactly one bit set in the specified
1949// constant.
1950static bool isOneBitSet(const ConstantInt *CI) {
1951 uint64_t V = CI->getRawValue();
1952 return V && (V & (V-1)) == 0;
1953}
1954
Chris Lattner8fc5af42004-09-23 21:46:38 +00001955#if 0 // Currently unused
1956// isLowOnes - Return true if the constant is of the form 0+1+.
1957static bool isLowOnes(const ConstantInt *CI) {
1958 uint64_t V = CI->getRawValue();
1959
1960 // There won't be bits set in parts that the type doesn't contain.
1961 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1962
1963 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1964 return U && V && (U & V) == 0;
1965}
1966#endif
1967
1968// isHighOnes - Return true if the constant is of the form 1+0+.
1969// This is the same as lowones(~X).
1970static bool isHighOnes(const ConstantInt *CI) {
1971 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001972 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001973
1974 // There won't be bits set in parts that the type doesn't contain.
1975 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1976
1977 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1978 return U && V && (U & V) == 0;
1979}
1980
1981
Chris Lattner3ac7c262003-08-13 20:16:26 +00001982/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1983/// are carefully arranged to allow folding of expressions such as:
1984///
1985/// (A < B) | (A > B) --> (A != B)
1986///
1987/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1988/// represents that the comparison is true if A == B, and bit value '1' is true
1989/// if A < B.
1990///
1991static unsigned getSetCondCode(const SetCondInst *SCI) {
1992 switch (SCI->getOpcode()) {
1993 // False -> 0
1994 case Instruction::SetGT: return 1;
1995 case Instruction::SetEQ: return 2;
1996 case Instruction::SetGE: return 3;
1997 case Instruction::SetLT: return 4;
1998 case Instruction::SetNE: return 5;
1999 case Instruction::SetLE: return 6;
2000 // True -> 7
2001 default:
2002 assert(0 && "Invalid SetCC opcode!");
2003 return 0;
2004 }
2005}
2006
2007/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2008/// opcode and two operands into either a constant true or false, or a brand new
2009/// SetCC instruction.
2010static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2011 switch (Opcode) {
2012 case 0: return ConstantBool::False;
2013 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2014 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2015 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2016 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2017 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2018 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2019 case 7: return ConstantBool::True;
2020 default: assert(0 && "Illegal SetCCCode!"); return 0;
2021 }
2022}
2023
2024// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2025struct FoldSetCCLogical {
2026 InstCombiner &IC;
2027 Value *LHS, *RHS;
2028 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2029 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2030 bool shouldApply(Value *V) const {
2031 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2032 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2033 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2034 return false;
2035 }
2036 Instruction *apply(BinaryOperator &Log) const {
2037 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2038 if (SCI->getOperand(0) != LHS) {
2039 assert(SCI->getOperand(1) == LHS);
2040 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2041 }
2042
2043 unsigned LHSCode = getSetCondCode(SCI);
2044 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2045 unsigned Code;
2046 switch (Log.getOpcode()) {
2047 case Instruction::And: Code = LHSCode & RHSCode; break;
2048 case Instruction::Or: Code = LHSCode | RHSCode; break;
2049 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002050 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002051 }
2052
2053 Value *RV = getSetCCValue(Code, LHS, RHS);
2054 if (Instruction *I = dyn_cast<Instruction>(RV))
2055 return I;
2056 // Otherwise, it's a constant boolean value...
2057 return IC.ReplaceInstUsesWith(Log, RV);
2058 }
2059};
2060
Chris Lattnerba1cb382003-09-19 17:17:26 +00002061// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2062// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2063// guaranteed to be either a shift instruction or a binary operator.
2064Instruction *InstCombiner::OptAndOp(Instruction *Op,
2065 ConstantIntegral *OpRHS,
2066 ConstantIntegral *AndRHS,
2067 BinaryOperator &TheAnd) {
2068 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002069 Constant *Together = 0;
2070 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002071 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002072
Chris Lattnerba1cb382003-09-19 17:17:26 +00002073 switch (Op->getOpcode()) {
2074 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002075 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002076 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2077 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002078 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002079 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002080 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002081 }
2082 break;
2083 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002084 if (Together == AndRHS) // (X | C) & C --> C
2085 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002086
Chris Lattner86102b82005-01-01 16:22:27 +00002087 if (Op->hasOneUse() && Together != OpRHS) {
2088 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2089 std::string Op0Name = Op->getName(); Op->setName("");
2090 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2091 InsertNewInstBefore(Or, TheAnd);
2092 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002093 }
2094 break;
2095 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002096 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002097 // Adding a one to a single bit bit-field should be turned into an XOR
2098 // of the bit. First thing to check is to see if this AND is with a
2099 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002100 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002101
2102 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002103 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002104
2105 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002106 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002107 // Ok, at this point, we know that we are masking the result of the
2108 // ADD down to exactly one bit. If the constant we are adding has
2109 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002110 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002111
Chris Lattnerba1cb382003-09-19 17:17:26 +00002112 // Check to see if any bits below the one bit set in AndRHSV are set.
2113 if ((AddRHS & (AndRHSV-1)) == 0) {
2114 // If not, the only thing that can effect the output of the AND is
2115 // the bit specified by AndRHSV. If that bit is set, the effect of
2116 // the XOR is to toggle the bit. If it is clear, then the ADD has
2117 // no effect.
2118 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2119 TheAnd.setOperand(0, X);
2120 return &TheAnd;
2121 } else {
2122 std::string Name = Op->getName(); Op->setName("");
2123 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002124 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002125 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002126 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002127 }
2128 }
2129 }
2130 }
2131 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002132
2133 case Instruction::Shl: {
2134 // We know that the AND will not produce any of the bits shifted in, so if
2135 // the anded constant includes them, clear them now!
2136 //
2137 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002138 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2139 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002140
Chris Lattner7e794272004-09-24 15:21:34 +00002141 if (CI == ShlMask) { // Masking out bits that the shift already masks
2142 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2143 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002144 TheAnd.setOperand(1, CI);
2145 return &TheAnd;
2146 }
2147 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002148 }
Chris Lattner2da29172003-09-19 19:05:02 +00002149 case Instruction::Shr:
2150 // We know that the AND will not produce any of the bits shifted in, so if
2151 // the anded constant includes them, clear them now! This only applies to
2152 // unsigned shifts, because a signed shr may bring in set bits!
2153 //
2154 if (AndRHS->getType()->isUnsigned()) {
2155 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002156 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2157 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2158
2159 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2160 return ReplaceInstUsesWith(TheAnd, Op);
2161 } else if (CI != AndRHS) {
2162 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002163 return &TheAnd;
2164 }
Chris Lattner7e794272004-09-24 15:21:34 +00002165 } else { // Signed shr.
2166 // See if this is shifting in some sign extension, then masking it out
2167 // with an and.
2168 if (Op->hasOneUse()) {
2169 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2170 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2171 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002172 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002173 // Make the argument unsigned.
2174 Value *ShVal = Op->getOperand(0);
2175 ShVal = InsertCastBefore(ShVal,
2176 ShVal->getType()->getUnsignedVersion(),
2177 TheAnd);
2178 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2179 OpRHS, Op->getName()),
2180 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002181 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2182 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2183 TheAnd.getName()),
2184 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002185 return new CastInst(ShVal, Op->getType());
2186 }
2187 }
Chris Lattner2da29172003-09-19 19:05:02 +00002188 }
2189 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002190 }
2191 return 0;
2192}
2193
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002194
Chris Lattner6862fbd2004-09-29 17:40:11 +00002195/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2196/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2197/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2198/// insert new instructions.
2199Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2200 bool Inside, Instruction &IB) {
2201 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2202 "Lo is not <= Hi in range emission code!");
2203 if (Inside) {
2204 if (Lo == Hi) // Trivially false.
2205 return new SetCondInst(Instruction::SetNE, V, V);
2206 if (cast<ConstantIntegral>(Lo)->isMinValue())
2207 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002208
Chris Lattner6862fbd2004-09-29 17:40:11 +00002209 Constant *AddCST = ConstantExpr::getNeg(Lo);
2210 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2211 InsertNewInstBefore(Add, IB);
2212 // Convert to unsigned for the comparison.
2213 const Type *UnsType = Add->getType()->getUnsignedVersion();
2214 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2215 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2216 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2217 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2218 }
2219
2220 if (Lo == Hi) // Trivially true.
2221 return new SetCondInst(Instruction::SetEQ, V, V);
2222
2223 Hi = SubOne(cast<ConstantInt>(Hi));
2224 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2225 return new SetCondInst(Instruction::SetGT, V, Hi);
2226
2227 // Emit X-Lo > Hi-Lo-1
2228 Constant *AddCST = ConstantExpr::getNeg(Lo);
2229 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2230 InsertNewInstBefore(Add, IB);
2231 // Convert to unsigned for the comparison.
2232 const Type *UnsType = Add->getType()->getUnsignedVersion();
2233 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2234 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2235 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2236 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2237}
2238
Chris Lattnerb4b25302005-09-18 07:22:02 +00002239// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2240// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2241// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2242// not, since all 1s are not contiguous.
2243static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2244 uint64_t V = Val->getRawValue();
2245 if (!isShiftedMask_64(V)) return false;
2246
2247 // look for the first zero bit after the run of ones
2248 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2249 // look for the first non-zero bit
2250 ME = 64-CountLeadingZeros_64(V);
2251 return true;
2252}
2253
2254
2255
2256/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2257/// where isSub determines whether the operator is a sub. If we can fold one of
2258/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002259///
2260/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2261/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2262/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2263///
2264/// return (A +/- B).
2265///
2266Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2267 ConstantIntegral *Mask, bool isSub,
2268 Instruction &I) {
2269 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2270 if (!LHSI || LHSI->getNumOperands() != 2 ||
2271 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2272
2273 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2274
2275 switch (LHSI->getOpcode()) {
2276 default: return 0;
2277 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002278 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2279 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2280 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2281 break;
2282
2283 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2284 // part, we don't need any explicit masks to take them out of A. If that
2285 // is all N is, ignore it.
2286 unsigned MB, ME;
2287 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002288 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2289 Mask >>= 64-MB+1;
2290 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002291 break;
2292 }
2293 }
Chris Lattneraf517572005-09-18 04:24:45 +00002294 return 0;
2295 case Instruction::Or:
2296 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002297 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2298 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2299 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002300 break;
2301 return 0;
2302 }
2303
2304 Instruction *New;
2305 if (isSub)
2306 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2307 else
2308 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2309 return InsertNewInstBefore(New, I);
2310}
2311
Chris Lattner113f4f42002-06-25 16:13:24 +00002312Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002313 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002315
Chris Lattner81a7a232004-10-16 18:11:37 +00002316 if (isa<UndefValue>(Op1)) // X & undef -> 0
2317 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2318
Chris Lattner86102b82005-01-01 16:22:27 +00002319 // and X, X = X
2320 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002321 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002322
Chris Lattner5b2edb12006-02-12 08:02:11 +00002323 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002324 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002325 uint64_t KnownZero, KnownOne;
2326 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2327 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002328 return &I;
2329
Chris Lattner86102b82005-01-01 16:22:27 +00002330 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002331 uint64_t AndRHSMask = AndRHS->getZExtValue();
2332 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002333 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002334
Chris Lattnerba1cb382003-09-19 17:17:26 +00002335 // Optimize a variety of ((val OP C1) & C2) combinations...
2336 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2337 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002338 Value *Op0LHS = Op0I->getOperand(0);
2339 Value *Op0RHS = Op0I->getOperand(1);
2340 switch (Op0I->getOpcode()) {
2341 case Instruction::Xor:
2342 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002343 // If the mask is only needed on one incoming arm, push it up.
2344 if (Op0I->hasOneUse()) {
2345 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2346 // Not masking anything out for the LHS, move to RHS.
2347 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2348 Op0RHS->getName()+".masked");
2349 InsertNewInstBefore(NewRHS, I);
2350 return BinaryOperator::create(
2351 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002352 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002353 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002354 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2355 // Not masking anything out for the RHS, move to LHS.
2356 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2357 Op0LHS->getName()+".masked");
2358 InsertNewInstBefore(NewLHS, I);
2359 return BinaryOperator::create(
2360 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2361 }
2362 }
2363
Chris Lattner86102b82005-01-01 16:22:27 +00002364 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002365 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002366 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2367 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2368 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2369 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2370 return BinaryOperator::createAnd(V, AndRHS);
2371 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2372 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002373 break;
2374
2375 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002376 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2377 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2378 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2379 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2380 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002381 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002382 }
2383
Chris Lattner16464b32003-07-23 19:25:52 +00002384 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002385 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002386 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002387 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2388 const Type *SrcTy = CI->getOperand(0)->getType();
2389
Chris Lattner2c14cf72005-08-07 07:03:10 +00002390 // If this is an integer truncation or change from signed-to-unsigned, and
2391 // if the source is an and/or with immediate, transform it. This
2392 // frequently occurs for bitfield accesses.
2393 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2394 if (SrcTy->getPrimitiveSizeInBits() >=
2395 I.getType()->getPrimitiveSizeInBits() &&
2396 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002397 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002398 if (CastOp->getOpcode() == Instruction::And) {
2399 // Change: and (cast (and X, C1) to T), C2
2400 // into : and (cast X to T), trunc(C1)&C2
2401 // This will folds the two ands together, which may allow other
2402 // simplifications.
2403 Instruction *NewCast =
2404 new CastInst(CastOp->getOperand(0), I.getType(),
2405 CastOp->getName()+".shrunk");
2406 NewCast = InsertNewInstBefore(NewCast, I);
2407
2408 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2409 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2410 return BinaryOperator::createAnd(NewCast, C3);
2411 } else if (CastOp->getOpcode() == Instruction::Or) {
2412 // Change: and (cast (or X, C1) to T), C2
2413 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2414 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2415 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2416 return ReplaceInstUsesWith(I, AndRHS);
2417 }
2418 }
Chris Lattner33217db2003-07-23 19:36:21 +00002419 }
Chris Lattner183b3362004-04-09 19:05:30 +00002420
2421 // Try to fold constant and into select arguments.
2422 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002423 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002424 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002425 if (isa<PHINode>(Op0))
2426 if (Instruction *NV = FoldOpIntoPhi(I))
2427 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002428 }
2429
Chris Lattnerbb74e222003-03-10 23:06:50 +00002430 Value *Op0NotVal = dyn_castNotVal(Op0);
2431 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002432
Chris Lattner023a4832004-06-18 06:07:51 +00002433 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2434 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2435
Misha Brukman9c003d82004-07-30 12:50:08 +00002436 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002437 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002438 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2439 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002440 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002441 return BinaryOperator::createNot(Or);
2442 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002443
2444 {
2445 Value *A = 0, *B = 0;
2446 ConstantInt *C1 = 0, *C2 = 0;
2447 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2448 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2449 return ReplaceInstUsesWith(I, Op1);
2450 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2451 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2452 return ReplaceInstUsesWith(I, Op0);
2453 }
2454
Chris Lattner3082c5a2003-02-18 19:28:33 +00002455
Chris Lattner623826c2004-09-28 21:48:02 +00002456 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2457 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002458 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2459 return R;
2460
Chris Lattner623826c2004-09-28 21:48:02 +00002461 Value *LHSVal, *RHSVal;
2462 ConstantInt *LHSCst, *RHSCst;
2463 Instruction::BinaryOps LHSCC, RHSCC;
2464 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2465 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2466 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2467 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002468 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00002469 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2470 // Ensure that the larger constant is on the RHS.
2471 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2472 SetCondInst *LHS = cast<SetCondInst>(Op0);
2473 if (cast<ConstantBool>(Cmp)->getValue()) {
2474 std::swap(LHS, RHS);
2475 std::swap(LHSCst, RHSCst);
2476 std::swap(LHSCC, RHSCC);
2477 }
2478
2479 // At this point, we know we have have two setcc instructions
2480 // comparing a value against two constants and and'ing the result
2481 // together. Because of the above check, we know that we only have
2482 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2483 // FoldSetCCLogical check above), that the two constants are not
2484 // equal.
2485 assert(LHSCst != RHSCst && "Compares not folded above?");
2486
2487 switch (LHSCC) {
2488 default: assert(0 && "Unknown integer condition code!");
2489 case Instruction::SetEQ:
2490 switch (RHSCC) {
2491 default: assert(0 && "Unknown integer condition code!");
2492 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2493 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2494 return ReplaceInstUsesWith(I, ConstantBool::False);
2495 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2496 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2497 return ReplaceInstUsesWith(I, LHS);
2498 }
2499 case Instruction::SetNE:
2500 switch (RHSCC) {
2501 default: assert(0 && "Unknown integer condition code!");
2502 case Instruction::SetLT:
2503 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2504 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2505 break; // (X != 13 & X < 15) -> no change
2506 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2507 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2508 return ReplaceInstUsesWith(I, RHS);
2509 case Instruction::SetNE:
2510 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2511 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2512 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2513 LHSVal->getName()+".off");
2514 InsertNewInstBefore(Add, I);
2515 const Type *UnsType = Add->getType()->getUnsignedVersion();
2516 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2517 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2518 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2519 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2520 }
2521 break; // (X != 13 & X != 15) -> no change
2522 }
2523 break;
2524 case Instruction::SetLT:
2525 switch (RHSCC) {
2526 default: assert(0 && "Unknown integer condition code!");
2527 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2528 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2529 return ReplaceInstUsesWith(I, ConstantBool::False);
2530 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2531 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2532 return ReplaceInstUsesWith(I, LHS);
2533 }
2534 case Instruction::SetGT:
2535 switch (RHSCC) {
2536 default: assert(0 && "Unknown integer condition code!");
2537 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2538 return ReplaceInstUsesWith(I, LHS);
2539 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2540 return ReplaceInstUsesWith(I, RHS);
2541 case Instruction::SetNE:
2542 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2543 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2544 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002545 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2546 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002547 }
2548 }
2549 }
2550 }
2551
Chris Lattner113f4f42002-06-25 16:13:24 +00002552 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002553}
2554
Chris Lattner113f4f42002-06-25 16:13:24 +00002555Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002556 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002558
Chris Lattner81a7a232004-10-16 18:11:37 +00002559 if (isa<UndefValue>(Op1))
2560 return ReplaceInstUsesWith(I, // X | undef -> -1
2561 ConstantIntegral::getAllOnesValue(I.getType()));
2562
Chris Lattner5b2edb12006-02-12 08:02:11 +00002563 // or X, X = X
2564 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002565 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002566
Chris Lattner5b2edb12006-02-12 08:02:11 +00002567 // See if we can simplify any instructions used by the instruction whose sole
2568 // purpose is to compute bits we don't care about.
2569 uint64_t KnownZero, KnownOne;
2570 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2571 KnownZero, KnownOne))
2572 return &I;
2573
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002574 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002575 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002576 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002577 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2578 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002579 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2580 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002581 InsertNewInstBefore(Or, I);
2582 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2583 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002584
Chris Lattnerd4252a72004-07-30 07:50:03 +00002585 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2586 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2587 std::string Op0Name = Op0->getName(); Op0->setName("");
2588 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2589 InsertNewInstBefore(Or, I);
2590 return BinaryOperator::createXor(Or,
2591 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002592 }
Chris Lattner183b3362004-04-09 19:05:30 +00002593
2594 // Try to fold constant and into select arguments.
2595 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002596 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002597 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002598 if (isa<PHINode>(Op0))
2599 if (Instruction *NV = FoldOpIntoPhi(I))
2600 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002601 }
2602
Chris Lattner330628a2006-01-06 17:59:59 +00002603 Value *A = 0, *B = 0;
2604 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002605
2606 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2607 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2608 return ReplaceInstUsesWith(I, Op1);
2609 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2610 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2611 return ReplaceInstUsesWith(I, Op0);
2612
Chris Lattnerb62f5082005-05-09 04:58:36 +00002613 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2614 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002615 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002616 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2617 Op0->setName("");
2618 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2619 }
2620
2621 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2622 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002623 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002624 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2625 Op0->setName("");
2626 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2627 }
2628
Chris Lattner15212982005-09-18 03:42:07 +00002629 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002630 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002631 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2632
2633 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2634 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2635
2636
Chris Lattner01f56c62005-09-18 06:02:59 +00002637 // If we have: ((V + N) & C1) | (V & C2)
2638 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2639 // replace with V+N.
2640 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002641 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00002642 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2643 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2644 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002645 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002646 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002647 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002648 return ReplaceInstUsesWith(I, A);
2649 }
2650 // Or commutes, try both ways.
2651 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2652 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2653 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002654 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002655 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002656 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00002657 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002658 }
2659 }
2660 }
Chris Lattner812aab72003-08-12 19:11:07 +00002661
Chris Lattnerd4252a72004-07-30 07:50:03 +00002662 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2663 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002664 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002665 ConstantIntegral::getAllOnesValue(I.getType()));
2666 } else {
2667 A = 0;
2668 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002669 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002670 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2671 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002672 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002673 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002674
Misha Brukman9c003d82004-07-30 12:50:08 +00002675 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002676 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2677 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2678 I.getName()+".demorgan"), I);
2679 return BinaryOperator::createNot(And);
2680 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002681 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002682
Chris Lattner3ac7c262003-08-13 20:16:26 +00002683 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002684 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002685 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2686 return R;
2687
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002688 Value *LHSVal, *RHSVal;
2689 ConstantInt *LHSCst, *RHSCst;
2690 Instruction::BinaryOps LHSCC, RHSCC;
2691 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2692 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2693 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2694 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002695 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002696 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2697 // Ensure that the larger constant is on the RHS.
2698 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2699 SetCondInst *LHS = cast<SetCondInst>(Op0);
2700 if (cast<ConstantBool>(Cmp)->getValue()) {
2701 std::swap(LHS, RHS);
2702 std::swap(LHSCst, RHSCst);
2703 std::swap(LHSCC, RHSCC);
2704 }
2705
2706 // At this point, we know we have have two setcc instructions
2707 // comparing a value against two constants and or'ing the result
2708 // together. Because of the above check, we know that we only have
2709 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2710 // FoldSetCCLogical check above), that the two constants are not
2711 // equal.
2712 assert(LHSCst != RHSCst && "Compares not folded above?");
2713
2714 switch (LHSCC) {
2715 default: assert(0 && "Unknown integer condition code!");
2716 case Instruction::SetEQ:
2717 switch (RHSCC) {
2718 default: assert(0 && "Unknown integer condition code!");
2719 case Instruction::SetEQ:
2720 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2721 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2722 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2723 LHSVal->getName()+".off");
2724 InsertNewInstBefore(Add, I);
2725 const Type *UnsType = Add->getType()->getUnsignedVersion();
2726 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2727 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2728 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2729 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2730 }
2731 break; // (X == 13 | X == 15) -> no change
2732
Chris Lattner5c219462005-04-19 06:04:18 +00002733 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2734 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002735 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2736 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2737 return ReplaceInstUsesWith(I, RHS);
2738 }
2739 break;
2740 case Instruction::SetNE:
2741 switch (RHSCC) {
2742 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002743 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2744 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2745 return ReplaceInstUsesWith(I, LHS);
2746 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002747 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002748 return ReplaceInstUsesWith(I, ConstantBool::True);
2749 }
2750 break;
2751 case Instruction::SetLT:
2752 switch (RHSCC) {
2753 default: assert(0 && "Unknown integer condition code!");
2754 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2755 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002756 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2757 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002758 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2759 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2760 return ReplaceInstUsesWith(I, RHS);
2761 }
2762 break;
2763 case Instruction::SetGT:
2764 switch (RHSCC) {
2765 default: assert(0 && "Unknown integer condition code!");
2766 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2767 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2768 return ReplaceInstUsesWith(I, LHS);
2769 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2770 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2771 return ReplaceInstUsesWith(I, ConstantBool::True);
2772 }
2773 }
2774 }
2775 }
Chris Lattner15212982005-09-18 03:42:07 +00002776
Chris Lattner113f4f42002-06-25 16:13:24 +00002777 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002778}
2779
Chris Lattnerc2076352004-02-16 01:20:27 +00002780// XorSelf - Implements: X ^ X --> 0
2781struct XorSelf {
2782 Value *RHS;
2783 XorSelf(Value *rhs) : RHS(rhs) {}
2784 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2785 Instruction *apply(BinaryOperator &Xor) const {
2786 return &Xor;
2787 }
2788};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002789
2790
Chris Lattner113f4f42002-06-25 16:13:24 +00002791Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002792 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002793 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002794
Chris Lattner81a7a232004-10-16 18:11:37 +00002795 if (isa<UndefValue>(Op1))
2796 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2797
Chris Lattnerc2076352004-02-16 01:20:27 +00002798 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2799 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2800 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002801 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002802 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00002803
2804 // See if we can simplify any instructions used by the instruction whose sole
2805 // purpose is to compute bits we don't care about.
2806 uint64_t KnownZero, KnownOne;
2807 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2808 KnownZero, KnownOne))
2809 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002810
Chris Lattner97638592003-07-23 21:37:07 +00002811 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00002812 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002813 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002814 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002815 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002816 return new SetCondInst(SCI->getInverseCondition(),
2817 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002818
Chris Lattner8f2f5982003-11-05 01:06:05 +00002819 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002820 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2821 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002822 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2823 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002824 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002825 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002826 }
Chris Lattner023a4832004-06-18 06:07:51 +00002827
2828 // ~(~X & Y) --> (X | ~Y)
2829 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2830 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2831 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2832 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002833 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002834 Op0I->getOperand(1)->getName()+".not");
2835 InsertNewInstBefore(NotY, I);
2836 return BinaryOperator::createOr(Op0NotVal, NotY);
2837 }
2838 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002839
Chris Lattner97638592003-07-23 21:37:07 +00002840 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00002841 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00002842 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002843 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002844 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2845 return BinaryOperator::createSub(
2846 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002847 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002848 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002849 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00002850 } else if (Op0I->getOpcode() == Instruction::Or) {
2851 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2852 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2853 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2854 // Anything in both C1 and C2 is known to be zero, remove it from
2855 // NewRHS.
2856 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2857 NewRHS = ConstantExpr::getAnd(NewRHS,
2858 ConstantExpr::getNot(CommonBits));
2859 WorkList.push_back(Op0I);
2860 I.setOperand(0, Op0I->getOperand(0));
2861 I.setOperand(1, NewRHS);
2862 return &I;
2863 }
Chris Lattner97638592003-07-23 21:37:07 +00002864 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002865 }
Chris Lattner183b3362004-04-09 19:05:30 +00002866
2867 // Try to fold constant and into select arguments.
2868 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002869 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002870 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002871 if (isa<PHINode>(Op0))
2872 if (Instruction *NV = FoldOpIntoPhi(I))
2873 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002874 }
2875
Chris Lattnerbb74e222003-03-10 23:06:50 +00002876 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002877 if (X == Op1)
2878 return ReplaceInstUsesWith(I,
2879 ConstantIntegral::getAllOnesValue(I.getType()));
2880
Chris Lattnerbb74e222003-03-10 23:06:50 +00002881 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002882 if (X == Op0)
2883 return ReplaceInstUsesWith(I,
2884 ConstantIntegral::getAllOnesValue(I.getType()));
2885
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002886 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002887 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002888 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2889 cast<BinaryOperator>(Op1I)->swapOperands();
2890 I.swapOperands();
2891 std::swap(Op0, Op1);
2892 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2893 I.swapOperands();
2894 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002895 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002896 } else if (Op1I->getOpcode() == Instruction::Xor) {
2897 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2898 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2899 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2900 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2901 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002902
2903 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002904 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002905 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2906 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002907 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002908 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2909 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002910 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002911 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002912 } else if (Op0I->getOpcode() == Instruction::Xor) {
2913 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2914 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2915 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2916 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002917 }
2918
Chris Lattner3ac7c262003-08-13 20:16:26 +00002919 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2920 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2921 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2922 return R;
2923
Chris Lattner113f4f42002-06-25 16:13:24 +00002924 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002925}
2926
Chris Lattner6862fbd2004-09-29 17:40:11 +00002927/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2928/// overflowed for this type.
2929static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2930 ConstantInt *In2) {
2931 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2932 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2933}
2934
2935static bool isPositive(ConstantInt *C) {
2936 return cast<ConstantSInt>(C)->getValue() >= 0;
2937}
2938
2939/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2940/// overflowed for this type.
2941static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2942 ConstantInt *In2) {
2943 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2944
2945 if (In1->getType()->isUnsigned())
2946 return cast<ConstantUInt>(Result)->getValue() <
2947 cast<ConstantUInt>(In1)->getValue();
2948 if (isPositive(In1) != isPositive(In2))
2949 return false;
2950 if (isPositive(In1))
2951 return cast<ConstantSInt>(Result)->getValue() <
2952 cast<ConstantSInt>(In1)->getValue();
2953 return cast<ConstantSInt>(Result)->getValue() >
2954 cast<ConstantSInt>(In1)->getValue();
2955}
2956
Chris Lattner0798af32005-01-13 20:14:25 +00002957/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2958/// code necessary to compute the offset from the base pointer (without adding
2959/// in the base pointer). Return the result as a signed integer of intptr size.
2960static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2961 TargetData &TD = IC.getTargetData();
2962 gep_type_iterator GTI = gep_type_begin(GEP);
2963 const Type *UIntPtrTy = TD.getIntPtrType();
2964 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2965 Value *Result = Constant::getNullValue(SIntPtrTy);
2966
2967 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00002968 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00002969
Chris Lattner0798af32005-01-13 20:14:25 +00002970 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2971 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002972 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002973 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2974 SIntPtrTy);
2975 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2976 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002977 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002978 Scale = ConstantExpr::getMul(OpC, Scale);
2979 if (Constant *RC = dyn_cast<Constant>(Result))
2980 Result = ConstantExpr::getAdd(RC, Scale);
2981 else {
2982 // Emit an add instruction.
2983 Result = IC.InsertNewInstBefore(
2984 BinaryOperator::createAdd(Result, Scale,
2985 GEP->getName()+".offs"), I);
2986 }
2987 }
2988 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002989 // Convert to correct type.
2990 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2991 Op->getName()+".c"), I);
2992 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002993 // We'll let instcombine(mul) convert this to a shl if possible.
2994 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2995 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002996
2997 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002998 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002999 GEP->getName()+".offs"), I);
3000 }
3001 }
3002 return Result;
3003}
3004
3005/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3006/// else. At this point we know that the GEP is on the LHS of the comparison.
3007Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3008 Instruction::BinaryOps Cond,
3009 Instruction &I) {
3010 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003011
3012 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3013 if (isa<PointerType>(CI->getOperand(0)->getType()))
3014 RHS = CI->getOperand(0);
3015
Chris Lattner0798af32005-01-13 20:14:25 +00003016 Value *PtrBase = GEPLHS->getOperand(0);
3017 if (PtrBase == RHS) {
3018 // As an optimization, we don't actually have to compute the actual value of
3019 // OFFSET if this is a seteq or setne comparison, just return whether each
3020 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003021 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3022 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003023 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3024 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003025 bool EmitIt = true;
3026 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3027 if (isa<UndefValue>(C)) // undef index -> undef.
3028 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3029 if (C->isNullValue())
3030 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003031 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3032 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003033 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003034 return ReplaceInstUsesWith(I, // No comparison is needed here.
3035 ConstantBool::get(Cond == Instruction::SetNE));
3036 }
3037
3038 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003039 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003040 new SetCondInst(Cond, GEPLHS->getOperand(i),
3041 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3042 if (InVal == 0)
3043 InVal = Comp;
3044 else {
3045 InVal = InsertNewInstBefore(InVal, I);
3046 InsertNewInstBefore(Comp, I);
3047 if (Cond == Instruction::SetNE) // True if any are unequal
3048 InVal = BinaryOperator::createOr(InVal, Comp);
3049 else // True if all are equal
3050 InVal = BinaryOperator::createAnd(InVal, Comp);
3051 }
3052 }
3053 }
3054
3055 if (InVal)
3056 return InVal;
3057 else
3058 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3059 ConstantBool::get(Cond == Instruction::SetEQ));
3060 }
Chris Lattner0798af32005-01-13 20:14:25 +00003061
3062 // Only lower this if the setcc is the only user of the GEP or if we expect
3063 // the result to fold to a constant!
3064 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3065 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3066 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3067 return new SetCondInst(Cond, Offset,
3068 Constant::getNullValue(Offset->getType()));
3069 }
3070 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003071 // If the base pointers are different, but the indices are the same, just
3072 // compare the base pointer.
3073 if (PtrBase != GEPRHS->getOperand(0)) {
3074 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003075 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003076 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003077 if (IndicesTheSame)
3078 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3079 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3080 IndicesTheSame = false;
3081 break;
3082 }
3083
3084 // If all indices are the same, just compare the base pointers.
3085 if (IndicesTheSame)
3086 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3087 GEPRHS->getOperand(0));
3088
3089 // Otherwise, the base pointers are different and the indices are
3090 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003091 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003092 }
Chris Lattner0798af32005-01-13 20:14:25 +00003093
Chris Lattner81e84172005-01-13 22:25:21 +00003094 // If one of the GEPs has all zero indices, recurse.
3095 bool AllZeros = true;
3096 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3097 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3098 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3099 AllZeros = false;
3100 break;
3101 }
3102 if (AllZeros)
3103 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3104 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003105
3106 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003107 AllZeros = true;
3108 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3109 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3110 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3111 AllZeros = false;
3112 break;
3113 }
3114 if (AllZeros)
3115 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3116
Chris Lattner4fa89822005-01-14 00:20:05 +00003117 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3118 // If the GEPs only differ by one index, compare it.
3119 unsigned NumDifferences = 0; // Keep track of # differences.
3120 unsigned DiffOperand = 0; // The operand that differs.
3121 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3122 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003123 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3124 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003125 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003126 NumDifferences = 2;
3127 break;
3128 } else {
3129 if (NumDifferences++) break;
3130 DiffOperand = i;
3131 }
3132 }
3133
3134 if (NumDifferences == 0) // SAME GEP?
3135 return ReplaceInstUsesWith(I, // No comparison is needed here.
3136 ConstantBool::get(Cond == Instruction::SetEQ));
3137 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003138 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3139 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003140
3141 // Convert the operands to signed values to make sure to perform a
3142 // signed comparison.
3143 const Type *NewTy = LHSV->getType()->getSignedVersion();
3144 if (LHSV->getType() != NewTy)
3145 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3146 LHSV->getName()), I);
3147 if (RHSV->getType() != NewTy)
3148 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3149 RHSV->getName()), I);
3150 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003151 }
3152 }
3153
Chris Lattner0798af32005-01-13 20:14:25 +00003154 // Only lower this if the setcc is the only user of the GEP or if we expect
3155 // the result to fold to a constant!
3156 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3157 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3158 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3159 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3160 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3161 return new SetCondInst(Cond, L, R);
3162 }
3163 }
3164 return 0;
3165}
3166
3167
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003168Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003169 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003170 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3171 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003172
3173 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003174 if (Op0 == Op1)
3175 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003176
Chris Lattner81a7a232004-10-16 18:11:37 +00003177 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3178 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3179
Chris Lattner15ff1e12004-11-14 07:33:16 +00003180 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3181 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003182 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3183 isa<ConstantPointerNull>(Op0)) &&
3184 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003185 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003186 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3187
3188 // setcc's with boolean values can always be turned into bitwise operations
3189 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003190 switch (I.getOpcode()) {
3191 default: assert(0 && "Invalid setcc instruction!");
3192 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003193 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003194 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003195 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003196 }
Chris Lattner4456da62004-08-11 00:50:51 +00003197 case Instruction::SetNE:
3198 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003199
Chris Lattner4456da62004-08-11 00:50:51 +00003200 case Instruction::SetGT:
3201 std::swap(Op0, Op1); // Change setgt -> setlt
3202 // FALL THROUGH
3203 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3204 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3205 InsertNewInstBefore(Not, I);
3206 return BinaryOperator::createAnd(Not, Op1);
3207 }
3208 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003209 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003210 // FALL THROUGH
3211 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3212 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3213 InsertNewInstBefore(Not, I);
3214 return BinaryOperator::createOr(Not, Op1);
3215 }
3216 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003217 }
3218
Chris Lattner2dd01742004-06-09 04:24:29 +00003219 // See if we are doing a comparison between a constant and an instruction that
3220 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003221 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003222 // Check to see if we are comparing against the minimum or maximum value...
3223 if (CI->isMinValue()) {
3224 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3225 return ReplaceInstUsesWith(I, ConstantBool::False);
3226 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3227 return ReplaceInstUsesWith(I, ConstantBool::True);
3228 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3229 return BinaryOperator::createSetEQ(Op0, Op1);
3230 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3231 return BinaryOperator::createSetNE(Op0, Op1);
3232
3233 } else if (CI->isMaxValue()) {
3234 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3235 return ReplaceInstUsesWith(I, ConstantBool::False);
3236 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3237 return ReplaceInstUsesWith(I, ConstantBool::True);
3238 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3239 return BinaryOperator::createSetEQ(Op0, Op1);
3240 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3241 return BinaryOperator::createSetNE(Op0, Op1);
3242
3243 // Comparing against a value really close to min or max?
3244 } else if (isMinValuePlusOne(CI)) {
3245 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3246 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3247 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3248 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3249
3250 } else if (isMaxValueMinusOne(CI)) {
3251 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3252 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3253 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3254 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3255 }
3256
3257 // If we still have a setle or setge instruction, turn it into the
3258 // appropriate setlt or setgt instruction. Since the border cases have
3259 // already been handled above, this requires little checking.
3260 //
3261 if (I.getOpcode() == Instruction::SetLE)
3262 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3263 if (I.getOpcode() == Instruction::SetGE)
3264 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3265
Chris Lattneree0f2802006-02-12 02:07:56 +00003266
3267 // See if we can fold the comparison based on bits known to be zero or one
3268 // in the input.
3269 uint64_t KnownZero, KnownOne;
3270 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3271 KnownZero, KnownOne, 0))
3272 return &I;
3273
3274 // Given the known and unknown bits, compute a range that the LHS could be
3275 // in.
3276 if (KnownOne | KnownZero) {
3277 if (Ty->isUnsigned()) { // Unsigned comparison.
3278 uint64_t Min, Max;
3279 uint64_t RHSVal = CI->getZExtValue();
3280 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3281 Min, Max);
3282 switch (I.getOpcode()) { // LE/GE have been folded already.
3283 default: assert(0 && "Unknown setcc opcode!");
3284 case Instruction::SetEQ:
3285 if (Max < RHSVal || Min > RHSVal)
3286 return ReplaceInstUsesWith(I, ConstantBool::False);
3287 break;
3288 case Instruction::SetNE:
3289 if (Max < RHSVal || Min > RHSVal)
3290 return ReplaceInstUsesWith(I, ConstantBool::True);
3291 break;
3292 case Instruction::SetLT:
3293 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3294 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3295 break;
3296 case Instruction::SetGT:
3297 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3298 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3299 break;
3300 }
3301 } else { // Signed comparison.
3302 int64_t Min, Max;
3303 int64_t RHSVal = CI->getSExtValue();
3304 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3305 Min, Max);
3306 switch (I.getOpcode()) { // LE/GE have been folded already.
3307 default: assert(0 && "Unknown setcc opcode!");
3308 case Instruction::SetEQ:
3309 if (Max < RHSVal || Min > RHSVal)
3310 return ReplaceInstUsesWith(I, ConstantBool::False);
3311 break;
3312 case Instruction::SetNE:
3313 if (Max < RHSVal || Min > RHSVal)
3314 return ReplaceInstUsesWith(I, ConstantBool::True);
3315 break;
3316 case Instruction::SetLT:
3317 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3318 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3319 break;
3320 case Instruction::SetGT:
3321 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3322 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3323 break;
3324 }
3325 }
3326 }
3327
3328
Chris Lattnere1e10e12004-05-25 06:32:08 +00003329 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003330 switch (LHSI->getOpcode()) {
3331 case Instruction::And:
3332 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3333 LHSI->getOperand(0)->hasOneUse()) {
3334 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3335 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3336 // happens a LOT in code produced by the C front-end, for bitfield
3337 // access.
3338 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003339 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3340
3341 // Check to see if there is a noop-cast between the shift and the and.
3342 if (!Shift) {
3343 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3344 if (CI->getOperand(0)->getType()->isIntegral() &&
3345 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3346 CI->getType()->getPrimitiveSizeInBits())
3347 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3348 }
3349
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003350 ConstantUInt *ShAmt;
3351 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003352 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3353 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003354
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003355 // We can fold this as long as we can't shift unknown bits
3356 // into the mask. This can only happen with signed shift
3357 // rights, as they sign-extend.
3358 if (ShAmt) {
3359 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003360 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003361 if (!CanFold) {
3362 // To test for the bad case of the signed shr, see if any
3363 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003364 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3365 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3366
3367 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003368 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003369 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3370 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003371 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3372 CanFold = true;
3373 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003374
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003375 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003376 Constant *NewCst;
3377 if (Shift->getOpcode() == Instruction::Shl)
3378 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3379 else
3380 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003381
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003382 // Check to see if we are shifting out any of the bits being
3383 // compared.
3384 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3385 // If we shifted bits out, the fold is not going to work out.
3386 // As a special case, check to see if this means that the
3387 // result is always true or false now.
3388 if (I.getOpcode() == Instruction::SetEQ)
3389 return ReplaceInstUsesWith(I, ConstantBool::False);
3390 if (I.getOpcode() == Instruction::SetNE)
3391 return ReplaceInstUsesWith(I, ConstantBool::True);
3392 } else {
3393 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003394 Constant *NewAndCST;
3395 if (Shift->getOpcode() == Instruction::Shl)
3396 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3397 else
3398 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3399 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003400 if (AndTy == Ty)
3401 LHSI->setOperand(0, Shift->getOperand(0));
3402 else {
3403 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3404 *Shift);
3405 LHSI->setOperand(0, NewCast);
3406 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003407 WorkList.push_back(Shift); // Shift is dead.
3408 AddUsesToWorkList(I);
3409 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003410 }
3411 }
Chris Lattner35167c32004-06-09 07:59:58 +00003412 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003413 }
3414 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003415
Chris Lattner272d5ca2004-09-28 18:22:15 +00003416 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3417 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3418 switch (I.getOpcode()) {
3419 default: break;
3420 case Instruction::SetEQ:
3421 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003422 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3423
3424 // Check that the shift amount is in range. If not, don't perform
3425 // undefined shifts. When the shift is visited it will be
3426 // simplified.
3427 if (ShAmt->getValue() >= TypeBits)
3428 break;
3429
Chris Lattner272d5ca2004-09-28 18:22:15 +00003430 // If we are comparing against bits always shifted out, the
3431 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003432 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003433 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3434 if (Comp != CI) {// Comparing against a bit that we know is zero.
3435 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3436 Constant *Cst = ConstantBool::get(IsSetNE);
3437 return ReplaceInstUsesWith(I, Cst);
3438 }
3439
3440 if (LHSI->hasOneUse()) {
3441 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003442 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003443 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3444
3445 Constant *Mask;
3446 if (CI->getType()->isUnsigned()) {
3447 Mask = ConstantUInt::get(CI->getType(), Val);
3448 } else if (ShAmtVal != 0) {
3449 Mask = ConstantSInt::get(CI->getType(), Val);
3450 } else {
3451 Mask = ConstantInt::getAllOnesValue(CI->getType());
3452 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003453
Chris Lattner272d5ca2004-09-28 18:22:15 +00003454 Instruction *AndI =
3455 BinaryOperator::createAnd(LHSI->getOperand(0),
3456 Mask, LHSI->getName()+".mask");
3457 Value *And = InsertNewInstBefore(AndI, I);
3458 return new SetCondInst(I.getOpcode(), And,
3459 ConstantExpr::getUShr(CI, ShAmt));
3460 }
3461 }
3462 }
3463 }
3464 break;
3465
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003466 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003467 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003468 switch (I.getOpcode()) {
3469 default: break;
3470 case Instruction::SetEQ:
3471 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003472
3473 // Check that the shift amount is in range. If not, don't perform
3474 // undefined shifts. When the shift is visited it will be
3475 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003476 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003477 if (ShAmt->getValue() >= TypeBits)
3478 break;
3479
Chris Lattner1023b872004-09-27 16:18:50 +00003480 // If we are comparing against bits always shifted out, the
3481 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003482 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003483 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003484
Chris Lattner1023b872004-09-27 16:18:50 +00003485 if (Comp != CI) {// Comparing against a bit that we know is zero.
3486 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3487 Constant *Cst = ConstantBool::get(IsSetNE);
3488 return ReplaceInstUsesWith(I, Cst);
3489 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003490
Chris Lattner1023b872004-09-27 16:18:50 +00003491 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003492 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003493
Chris Lattner1023b872004-09-27 16:18:50 +00003494 // Otherwise strength reduce the shift into an and.
3495 uint64_t Val = ~0ULL; // All ones.
3496 Val <<= ShAmtVal; // Shift over to the right spot.
3497
3498 Constant *Mask;
3499 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003500 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003501 Mask = ConstantUInt::get(CI->getType(), Val);
3502 } else {
3503 Mask = ConstantSInt::get(CI->getType(), Val);
3504 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003505
Chris Lattner1023b872004-09-27 16:18:50 +00003506 Instruction *AndI =
3507 BinaryOperator::createAnd(LHSI->getOperand(0),
3508 Mask, LHSI->getName()+".mask");
3509 Value *And = InsertNewInstBefore(AndI, I);
3510 return new SetCondInst(I.getOpcode(), And,
3511 ConstantExpr::getShl(CI, ShAmt));
3512 }
3513 break;
3514 }
3515 }
3516 }
3517 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003518
Chris Lattner6862fbd2004-09-29 17:40:11 +00003519 case Instruction::Div:
3520 // Fold: (div X, C1) op C2 -> range check
3521 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3522 // Fold this div into the comparison, producing a range check.
3523 // Determine, based on the divide type, what the range is being
3524 // checked. If there is an overflow on the low or high side, remember
3525 // it, otherwise compute the range [low, hi) bounding the new value.
3526 bool LoOverflow = false, HiOverflow = 0;
3527 ConstantInt *LoBound = 0, *HiBound = 0;
3528
3529 ConstantInt *Prod;
3530 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3531
Chris Lattnera92af962004-10-11 19:40:04 +00003532 Instruction::BinaryOps Opcode = I.getOpcode();
3533
Chris Lattner6862fbd2004-09-29 17:40:11 +00003534 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3535 } else if (LHSI->getType()->isUnsigned()) { // udiv
3536 LoBound = Prod;
3537 LoOverflow = ProdOV;
3538 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3539 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3540 if (CI->isNullValue()) { // (X / pos) op 0
3541 // Can't overflow.
3542 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3543 HiBound = DivRHS;
3544 } else if (isPositive(CI)) { // (X / pos) op pos
3545 LoBound = Prod;
3546 LoOverflow = ProdOV;
3547 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3548 } else { // (X / pos) op neg
3549 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3550 LoOverflow = AddWithOverflow(LoBound, Prod,
3551 cast<ConstantInt>(DivRHSH));
3552 HiBound = Prod;
3553 HiOverflow = ProdOV;
3554 }
3555 } else { // Divisor is < 0.
3556 if (CI->isNullValue()) { // (X / neg) op 0
3557 LoBound = AddOne(DivRHS);
3558 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003559 if (HiBound == DivRHS)
3560 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003561 } else if (isPositive(CI)) { // (X / neg) op pos
3562 HiOverflow = LoOverflow = ProdOV;
3563 if (!LoOverflow)
3564 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3565 HiBound = AddOne(Prod);
3566 } else { // (X / neg) op neg
3567 LoBound = Prod;
3568 LoOverflow = HiOverflow = ProdOV;
3569 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3570 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003571
Chris Lattnera92af962004-10-11 19:40:04 +00003572 // Dividing by a negate swaps the condition.
3573 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00003574 }
3575
3576 if (LoBound) {
3577 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00003578 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003579 default: assert(0 && "Unhandled setcc opcode!");
3580 case Instruction::SetEQ:
3581 if (LoOverflow && HiOverflow)
3582 return ReplaceInstUsesWith(I, ConstantBool::False);
3583 else if (HiOverflow)
3584 return new SetCondInst(Instruction::SetGE, X, LoBound);
3585 else if (LoOverflow)
3586 return new SetCondInst(Instruction::SetLT, X, HiBound);
3587 else
3588 return InsertRangeTest(X, LoBound, HiBound, true, I);
3589 case Instruction::SetNE:
3590 if (LoOverflow && HiOverflow)
3591 return ReplaceInstUsesWith(I, ConstantBool::True);
3592 else if (HiOverflow)
3593 return new SetCondInst(Instruction::SetLT, X, LoBound);
3594 else if (LoOverflow)
3595 return new SetCondInst(Instruction::SetGE, X, HiBound);
3596 else
3597 return InsertRangeTest(X, LoBound, HiBound, false, I);
3598 case Instruction::SetLT:
3599 if (LoOverflow)
3600 return ReplaceInstUsesWith(I, ConstantBool::False);
3601 return new SetCondInst(Instruction::SetLT, X, LoBound);
3602 case Instruction::SetGT:
3603 if (HiOverflow)
3604 return ReplaceInstUsesWith(I, ConstantBool::False);
3605 return new SetCondInst(Instruction::SetGE, X, HiBound);
3606 }
3607 }
3608 }
3609 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003610 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003611
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003612 // Simplify seteq and setne instructions...
3613 if (I.getOpcode() == Instruction::SetEQ ||
3614 I.getOpcode() == Instruction::SetNE) {
3615 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3616
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003617 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003618 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003619 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3620 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003621 case Instruction::Rem:
3622 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3623 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3624 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003625 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3626 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3627 if (isPowerOf2_64(V)) {
3628 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003629 const Type *UTy = BO->getType()->getUnsignedVersion();
3630 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3631 UTy, "tmp"), I);
3632 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3633 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3634 RHSCst, BO->getName()), I);
3635 return BinaryOperator::create(I.getOpcode(), NewRem,
3636 Constant::getNullValue(UTy));
3637 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003638 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003639 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003640
Chris Lattnerc992add2003-08-13 05:33:12 +00003641 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003642 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3643 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003644 if (BO->hasOneUse())
3645 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3646 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003647 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003648 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3649 // efficiently invertible, or if the add has just this one use.
3650 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003651
Chris Lattnerc992add2003-08-13 05:33:12 +00003652 if (Value *NegVal = dyn_castNegVal(BOp1))
3653 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3654 else if (Value *NegVal = dyn_castNegVal(BOp0))
3655 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003656 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003657 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3658 BO->setName("");
3659 InsertNewInstBefore(Neg, I);
3660 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3661 }
3662 }
3663 break;
3664 case Instruction::Xor:
3665 // For the xor case, we can xor two constants together, eliminating
3666 // the explicit xor.
3667 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3668 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003669 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003670
3671 // FALLTHROUGH
3672 case Instruction::Sub:
3673 // Replace (([sub|xor] A, B) != 0) with (A != B)
3674 if (CI->isNullValue())
3675 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3676 BO->getOperand(1));
3677 break;
3678
3679 case Instruction::Or:
3680 // If bits are being or'd in that are not present in the constant we
3681 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003682 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003683 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003684 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003685 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003686 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003687 break;
3688
3689 case Instruction::And:
3690 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003691 // If bits are being compared against that are and'd out, then the
3692 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003693 if (!ConstantExpr::getAnd(CI,
3694 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003695 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003696
Chris Lattner35167c32004-06-09 07:59:58 +00003697 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003698 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003699 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3700 Instruction::SetNE, Op0,
3701 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003702
Chris Lattnerc992add2003-08-13 05:33:12 +00003703 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3704 // to be a signed value as appropriate.
3705 if (isSignBit(BOC)) {
3706 Value *X = BO->getOperand(0);
3707 // If 'X' is not signed, insert a cast now...
3708 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003709 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003710 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003711 }
3712 return new SetCondInst(isSetNE ? Instruction::SetLT :
3713 Instruction::SetGE, X,
3714 Constant::getNullValue(X->getType()));
3715 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003716
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003717 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003718 if (CI->isNullValue() && isHighOnes(BOC)) {
3719 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003720 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003721
3722 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003723 if (NegX->getType()->isSigned()) {
3724 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3725 X = InsertCastBefore(X, DestTy, I);
3726 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003727 }
3728
3729 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003730 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003731 }
3732
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003733 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003734 default: break;
3735 }
3736 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003737 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003738 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003739 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3740 Value *CastOp = Cast->getOperand(0);
3741 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003742 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003743 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003744 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003745 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003746 "Source and destination signednesses should differ!");
3747 if (Cast->getType()->isSigned()) {
3748 // If this is a signed comparison, check for comparisons in the
3749 // vicinity of zero.
3750 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3751 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003752 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003753 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003754 else if (I.getOpcode() == Instruction::SetGT &&
3755 cast<ConstantSInt>(CI)->getValue() == -1)
3756 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003757 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003758 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003759 } else {
3760 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3761 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003762 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003763 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003764 return BinaryOperator::createSetGT(CastOp,
3765 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003766 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003767 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003768 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003769 return BinaryOperator::createSetLT(CastOp,
3770 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003771 }
3772 }
3773 }
Chris Lattnere967b342003-06-04 05:10:11 +00003774 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003775 }
3776
Chris Lattner77c32c32005-04-23 15:31:55 +00003777 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3778 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3779 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3780 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003781 case Instruction::GetElementPtr:
3782 if (RHSC->isNullValue()) {
3783 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3784 bool isAllZeros = true;
3785 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3786 if (!isa<Constant>(LHSI->getOperand(i)) ||
3787 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3788 isAllZeros = false;
3789 break;
3790 }
3791 if (isAllZeros)
3792 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3793 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3794 }
3795 break;
3796
Chris Lattner77c32c32005-04-23 15:31:55 +00003797 case Instruction::PHI:
3798 if (Instruction *NV = FoldOpIntoPhi(I))
3799 return NV;
3800 break;
3801 case Instruction::Select:
3802 // If either operand of the select is a constant, we can fold the
3803 // comparison into the select arms, which will cause one to be
3804 // constant folded and the select turned into a bitwise or.
3805 Value *Op1 = 0, *Op2 = 0;
3806 if (LHSI->hasOneUse()) {
3807 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3808 // Fold the known value into the constant operand.
3809 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3810 // Insert a new SetCC of the other select operand.
3811 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3812 LHSI->getOperand(2), RHSC,
3813 I.getName()), I);
3814 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3815 // Fold the known value into the constant operand.
3816 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3817 // Insert a new SetCC of the other select operand.
3818 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3819 LHSI->getOperand(1), RHSC,
3820 I.getName()), I);
3821 }
3822 }
Jeff Cohen82639852005-04-23 21:38:35 +00003823
Chris Lattner77c32c32005-04-23 15:31:55 +00003824 if (Op1)
3825 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3826 break;
3827 }
3828 }
3829
Chris Lattner0798af32005-01-13 20:14:25 +00003830 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3831 if (User *GEP = dyn_castGetElementPtr(Op0))
3832 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3833 return NI;
3834 if (User *GEP = dyn_castGetElementPtr(Op1))
3835 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3836 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3837 return NI;
3838
Chris Lattner16930792003-11-03 04:25:02 +00003839 // Test to see if the operands of the setcc are casted versions of other
3840 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003841 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3842 Value *CastOp0 = CI->getOperand(0);
3843 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003844 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003845 (I.getOpcode() == Instruction::SetEQ ||
3846 I.getOpcode() == Instruction::SetNE)) {
3847 // We keep moving the cast from the left operand over to the right
3848 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003849 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003850
Chris Lattner16930792003-11-03 04:25:02 +00003851 // If operand #1 is a cast instruction, see if we can eliminate it as
3852 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003853 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3854 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003855 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003856 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003857
Chris Lattner16930792003-11-03 04:25:02 +00003858 // If Op1 is a constant, we can fold the cast into the constant.
3859 if (Op1->getType() != Op0->getType())
3860 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3861 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3862 } else {
3863 // Otherwise, cast the RHS right before the setcc
3864 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3865 InsertNewInstBefore(cast<Instruction>(Op1), I);
3866 }
3867 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3868 }
3869
Chris Lattner6444c372003-11-03 05:17:03 +00003870 // Handle the special case of: setcc (cast bool to X), <cst>
3871 // This comes up when you have code like
3872 // int X = A < B;
3873 // if (X) ...
3874 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003875 // with a constant or another cast from the same type.
3876 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3877 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3878 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003879 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00003880
3881 if (I.getOpcode() == Instruction::SetNE ||
3882 I.getOpcode() == Instruction::SetEQ) {
3883 Value *A, *B;
3884 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3885 (A == Op1 || B == Op1)) {
3886 // (A^B) == A -> B == 0
3887 Value *OtherVal = A == Op1 ? B : A;
3888 return BinaryOperator::create(I.getOpcode(), OtherVal,
3889 Constant::getNullValue(A->getType()));
3890 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3891 (A == Op0 || B == Op0)) {
3892 // A == (A^B) -> B == 0
3893 Value *OtherVal = A == Op0 ? B : A;
3894 return BinaryOperator::create(I.getOpcode(), OtherVal,
3895 Constant::getNullValue(A->getType()));
3896 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
3897 // (A-B) == A -> B == 0
3898 return BinaryOperator::create(I.getOpcode(), B,
3899 Constant::getNullValue(B->getType()));
3900 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
3901 // A == (A-B) -> B == 0
3902 return BinaryOperator::create(I.getOpcode(), B,
3903 Constant::getNullValue(B->getType()));
3904 }
3905 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003906 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003907}
3908
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003909// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3910// We only handle extending casts so far.
3911//
3912Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3913 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3914 const Type *SrcTy = LHSCIOp->getType();
3915 const Type *DestTy = SCI.getOperand(0)->getType();
3916 Value *RHSCIOp;
3917
3918 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003919 return 0;
3920
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003921 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3922 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3923 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3924
3925 // Is this a sign or zero extension?
3926 bool isSignSrc = SrcTy->isSigned();
3927 bool isSignDest = DestTy->isSigned();
3928
3929 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3930 // Not an extension from the same type?
3931 RHSCIOp = CI->getOperand(0);
3932 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3933 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3934 // Compute the constant that would happen if we truncated to SrcTy then
3935 // reextended to DestTy.
3936 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3937
3938 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3939 RHSCIOp = Res;
3940 } else {
3941 // If the value cannot be represented in the shorter type, we cannot emit
3942 // a simple comparison.
3943 if (SCI.getOpcode() == Instruction::SetEQ)
3944 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3945 if (SCI.getOpcode() == Instruction::SetNE)
3946 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3947
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003948 // Evaluate the comparison for LT.
3949 Value *Result;
3950 if (DestTy->isSigned()) {
3951 // We're performing a signed comparison.
3952 if (isSignSrc) {
3953 // Signed extend and signed comparison.
3954 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3955 Result = ConstantBool::False;
3956 else
3957 Result = ConstantBool::True; // X < (large) --> true
3958 } else {
3959 // Unsigned extend and signed comparison.
3960 if (cast<ConstantSInt>(CI)->getValue() < 0)
3961 Result = ConstantBool::False;
3962 else
3963 Result = ConstantBool::True;
3964 }
3965 } else {
3966 // We're performing an unsigned comparison.
3967 if (!isSignSrc) {
3968 // Unsigned extend & compare -> always true.
3969 Result = ConstantBool::True;
3970 } else {
3971 // We're performing an unsigned comp with a sign extended value.
3972 // This is true if the input is >= 0. [aka >s -1]
3973 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3974 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3975 NegOne, SCI.getName()), SCI);
3976 }
Reid Spencer279fa252004-11-28 21:31:15 +00003977 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003978
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003979 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003980 if (SCI.getOpcode() == Instruction::SetLT) {
3981 return ReplaceInstUsesWith(SCI, Result);
3982 } else {
3983 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3984 if (Constant *CI = dyn_cast<Constant>(Result))
3985 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3986 else
3987 return BinaryOperator::createNot(Result);
3988 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003989 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003990 } else {
3991 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003992 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003993
Chris Lattner252a8452005-06-16 03:00:08 +00003994 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003995 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3996}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003997
Chris Lattnere8d6c602003-03-10 19:16:08 +00003998Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003999 assert(I.getOperand(1)->getType() == Type::UByteTy);
4000 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004001 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004002
4003 // shl X, 0 == X and shr X, 0 == X
4004 // shl 0, X == 0 and shr 0, X == 0
4005 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004006 Op0 == Constant::getNullValue(Op0->getType()))
4007 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004008
Chris Lattner81a7a232004-10-16 18:11:37 +00004009 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4010 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004011 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004012 else // undef << X -> 0 AND undef >>u X -> 0
4013 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4014 }
4015 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004016 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4018 else
4019 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4020 }
4021
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004022 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4023 if (!isLeftShift)
4024 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4025 if (CSI->isAllOnesValue())
4026 return ReplaceInstUsesWith(I, CSI);
4027
Chris Lattner183b3362004-04-09 19:05:30 +00004028 // Try to fold constant and into select arguments.
4029 if (isa<Constant>(Op0))
4030 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004031 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004032 return R;
4033
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004034 // See if we can turn a signed shr into an unsigned shr.
4035 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004036 if (MaskedValueIsZero(Op0,
4037 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004038 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4039 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4040 I.getName()), I);
4041 return new CastInst(V, I.getType());
4042 }
4043 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004044
Chris Lattner14553932006-01-06 07:12:35 +00004045 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4046 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4047 return Res;
4048 return 0;
4049}
4050
4051Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4052 ShiftInst &I) {
4053 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004054 bool isSignedShift = Op0->getType()->isSigned();
4055 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004056
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004057 // See if we can simplify any instructions used by the instruction whose sole
4058 // purpose is to compute bits we don't care about.
4059 uint64_t KnownZero, KnownOne;
4060 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4061 KnownZero, KnownOne))
4062 return &I;
4063
Chris Lattner14553932006-01-06 07:12:35 +00004064 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4065 // of a signed value.
4066 //
4067 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4068 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004069 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004070 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4071 else {
4072 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4073 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004074 }
Chris Lattner14553932006-01-06 07:12:35 +00004075 }
4076
4077 // ((X*C1) << C2) == (X * (C1 << C2))
4078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4079 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4080 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4081 return BinaryOperator::createMul(BO->getOperand(0),
4082 ConstantExpr::getShl(BOOp, Op1));
4083
4084 // Try to fold constant and into select arguments.
4085 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4086 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4087 return R;
4088 if (isa<PHINode>(Op0))
4089 if (Instruction *NV = FoldOpIntoPhi(I))
4090 return NV;
4091
4092 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004093 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4094 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4095 Value *V1, *V2;
4096 ConstantInt *CC;
4097 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004098 default: break;
4099 case Instruction::Add:
4100 case Instruction::And:
4101 case Instruction::Or:
4102 case Instruction::Xor:
4103 // These operators commute.
4104 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004105 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4106 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004107 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004108 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004109 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004110 Op0BO->getName());
4111 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004112 Instruction *X =
4113 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4114 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004115 InsertNewInstBefore(X, I); // (X + (Y << C))
4116 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004117 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004118 return BinaryOperator::createAnd(X, C2);
4119 }
Chris Lattner14553932006-01-06 07:12:35 +00004120
Chris Lattner797dee72005-09-18 06:30:59 +00004121 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4122 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4123 match(Op0BO->getOperand(1),
4124 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004125 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004126 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004127 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004128 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004129 Op0BO->getName());
4130 InsertNewInstBefore(YS, I); // (Y << C)
4131 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004132 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004133 V1->getName()+".mask");
4134 InsertNewInstBefore(XM, I); // X & (CC << C)
4135
4136 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4137 }
Chris Lattner14553932006-01-06 07:12:35 +00004138
Chris Lattner797dee72005-09-18 06:30:59 +00004139 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004140 case Instruction::Sub:
4141 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004142 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4143 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004144 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004145 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004146 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004147 Op0BO->getName());
4148 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004149 Instruction *X =
4150 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4151 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004152 InsertNewInstBefore(X, I); // (X + (Y << C))
4153 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004154 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004155 return BinaryOperator::createAnd(X, C2);
4156 }
Chris Lattner14553932006-01-06 07:12:35 +00004157
Chris Lattner797dee72005-09-18 06:30:59 +00004158 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4159 match(Op0BO->getOperand(0),
4160 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004161 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004162 cast<BinaryOperator>(Op0BO->getOperand(0))
4163 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004164 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004165 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004166 Op0BO->getName());
4167 InsertNewInstBefore(YS, I); // (Y << C)
4168 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004169 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004170 V1->getName()+".mask");
4171 InsertNewInstBefore(XM, I); // X & (CC << C)
4172
4173 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4174 }
Chris Lattner14553932006-01-06 07:12:35 +00004175
Chris Lattner27cb9db2005-09-18 05:12:10 +00004176 break;
Chris Lattner14553932006-01-06 07:12:35 +00004177 }
4178
4179
4180 // If the operand is an bitwise operator with a constant RHS, and the
4181 // shift is the only use, we can pull it out of the shift.
4182 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4183 bool isValid = true; // Valid only for And, Or, Xor
4184 bool highBitSet = false; // Transform if high bit of constant set?
4185
4186 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004187 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004188 case Instruction::Add:
4189 isValid = isLeftShift;
4190 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004191 case Instruction::Or:
4192 case Instruction::Xor:
4193 highBitSet = false;
4194 break;
4195 case Instruction::And:
4196 highBitSet = true;
4197 break;
Chris Lattner14553932006-01-06 07:12:35 +00004198 }
4199
4200 // If this is a signed shift right, and the high bit is modified
4201 // by the logical operation, do not perform the transformation.
4202 // The highBitSet boolean indicates the value of the high bit of
4203 // the constant which would cause it to be modified for this
4204 // operation.
4205 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004206 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004207 uint64_t Val = Op0C->getRawValue();
4208 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4209 }
4210
4211 if (isValid) {
4212 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4213
4214 Instruction *NewShift =
4215 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4216 Op0BO->getName());
4217 Op0BO->setName("");
4218 InsertNewInstBefore(NewShift, I);
4219
4220 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4221 NewRHS);
4222 }
4223 }
4224 }
4225 }
4226
Chris Lattnereb372a02006-01-06 07:52:12 +00004227 // Find out if this is a shift of a shift by a constant.
4228 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004229 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004230 ShiftOp = Op0SI;
4231 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4232 // If this is a noop-integer case of a shift instruction, use the shift.
4233 if (CI->getOperand(0)->getType()->isInteger() &&
4234 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4235 CI->getType()->getPrimitiveSizeInBits() &&
4236 isa<ShiftInst>(CI->getOperand(0))) {
4237 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4238 }
4239 }
4240
4241 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4242 // Find the operands and properties of the input shift. Note that the
4243 // signedness of the input shift may differ from the current shift if there
4244 // is a noop cast between the two.
4245 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4246 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004247 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004248
4249 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4250
4251 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4252 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4253
4254 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4255 if (isLeftShift == isShiftOfLeftShift) {
4256 // Do not fold these shifts if the first one is signed and the second one
4257 // is unsigned and this is a right shift. Further, don't do any folding
4258 // on them.
4259 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4260 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004261
Chris Lattnereb372a02006-01-06 07:52:12 +00004262 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4263 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4264 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004265
Chris Lattnereb372a02006-01-06 07:52:12 +00004266 Value *Op = ShiftOp->getOperand(0);
4267 if (isShiftOfSignedShift != isSignedShift)
4268 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4269 return new ShiftInst(I.getOpcode(), Op,
4270 ConstantUInt::get(Type::UByteTy, Amt));
4271 }
4272
4273 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4274 // signed types, we can only support the (A >> c1) << c2 configuration,
4275 // because it can not turn an arbitrary bit of A into a sign bit.
4276 if (isUnsignedShift || isLeftShift) {
4277 // Calculate bitmask for what gets shifted off the edge.
4278 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4279 if (isLeftShift)
4280 C = ConstantExpr::getShl(C, ShiftAmt1C);
4281 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004282 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004283
4284 Value *Op = ShiftOp->getOperand(0);
4285 if (isShiftOfSignedShift != isSignedShift)
4286 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4287
4288 Instruction *Mask =
4289 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4290 InsertNewInstBefore(Mask, I);
4291
4292 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004293 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004294 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004295 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004296 return new ShiftInst(I.getOpcode(), Mask,
4297 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004298 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4299 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4300 // Make sure to emit an unsigned shift right, not a signed one.
4301 Mask = InsertNewInstBefore(new CastInst(Mask,
4302 Mask->getType()->getUnsignedVersion(),
4303 Op->getName()), I);
4304 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004305 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004306 InsertNewInstBefore(Mask, I);
4307 return new CastInst(Mask, I.getType());
4308 } else {
4309 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4310 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4311 }
4312 } else {
4313 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4314 Op = InsertNewInstBefore(new CastInst(Mask,
4315 I.getType()->getSignedVersion(),
4316 Mask->getName()), I);
4317 Instruction *Shift =
4318 new ShiftInst(ShiftOp->getOpcode(), Op,
4319 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4320 InsertNewInstBefore(Shift, I);
4321
4322 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4323 C = ConstantExpr::getShl(C, Op1);
4324 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4325 InsertNewInstBefore(Mask, I);
4326 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004327 }
4328 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004329 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004330 // this case, C1 == C2 and C1 is 8, 16, or 32.
4331 if (ShiftAmt1 == ShiftAmt2) {
4332 const Type *SExtType = 0;
4333 switch (ShiftAmt1) {
4334 case 8 : SExtType = Type::SByteTy; break;
4335 case 16: SExtType = Type::ShortTy; break;
4336 case 32: SExtType = Type::IntTy; break;
4337 }
4338
4339 if (SExtType) {
4340 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4341 SExtType, "sext");
4342 InsertNewInstBefore(NewTrunc, I);
4343 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004344 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004345 }
Chris Lattner86102b82005-01-01 16:22:27 +00004346 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004347 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004348 return 0;
4349}
4350
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004351enum CastType {
4352 Noop = 0,
4353 Truncate = 1,
4354 Signext = 2,
4355 Zeroext = 3
4356};
4357
4358/// getCastType - In the future, we will split the cast instruction into these
4359/// various types. Until then, we have to do the analysis here.
4360static CastType getCastType(const Type *Src, const Type *Dest) {
4361 assert(Src->isIntegral() && Dest->isIntegral() &&
4362 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004363 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4364 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004365
4366 if (SrcSize == DestSize) return Noop;
4367 if (SrcSize > DestSize) return Truncate;
4368 if (Src->isSigned()) return Signext;
4369 return Zeroext;
4370}
4371
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004372
Chris Lattner48a44f72002-05-02 17:06:02 +00004373// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4374// instruction.
4375//
Chris Lattnere154abf2006-01-19 07:40:22 +00004376static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4377 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004378
Chris Lattner650b6da2002-08-02 20:00:25 +00004379 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00004380 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00004381 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00004382 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00004383 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00004384
Chris Lattner4fbad962004-07-21 04:27:24 +00004385 // If we are casting between pointer and integer types, treat pointers as
4386 // integers of the appropriate size for the code below.
4387 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4388 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4389 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00004390
Chris Lattner48a44f72002-05-02 17:06:02 +00004391 // Allow free casting and conversion of sizes as long as the sign doesn't
4392 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004393 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004394 CastType FirstCast = getCastType(SrcTy, MidTy);
4395 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00004396
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004397 // Capture the effect of these two casts. If the result is a legal cast,
4398 // the CastType is stored here, otherwise a special code is used.
4399 static const unsigned CastResult[] = {
4400 // First cast is noop
4401 0, 1, 2, 3,
4402 // First cast is a truncate
4403 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4404 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00004405 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004406 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00004407 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00004408 };
4409
4410 unsigned Result = CastResult[FirstCast*4+SecondCast];
4411 switch (Result) {
4412 default: assert(0 && "Illegal table value!");
4413 case 0:
4414 case 1:
4415 case 2:
4416 case 3:
4417 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4418 // truncates, we could eliminate more casts.
4419 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4420 case 4:
4421 return false; // Not possible to eliminate this here.
4422 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00004423 // Sign or zero extend followed by truncate is always ok if the result
4424 // is a truncate or noop.
4425 CastType ResultCast = getCastType(SrcTy, DstTy);
4426 if (ResultCast == Noop || ResultCast == Truncate)
4427 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004428 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00004429 // result will match the sign/zeroextendness of the result.
4430 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00004431 }
Chris Lattner650b6da2002-08-02 20:00:25 +00004432 }
Chris Lattnere154abf2006-01-19 07:40:22 +00004433
4434 // If this is a cast from 'float -> double -> integer', cast from
4435 // 'float -> integer' directly, as the value isn't changed by the
4436 // float->double conversion.
4437 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4438 DstTy->isIntegral() &&
4439 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4440 return true;
4441
Chris Lattner48a44f72002-05-02 17:06:02 +00004442 return false;
4443}
4444
Chris Lattner11ffd592004-07-20 05:21:00 +00004445static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004446 if (V->getType() == Ty || isa<Constant>(V)) return false;
4447 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00004448 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4449 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004450 return false;
4451 return true;
4452}
4453
4454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4455/// InsertBefore instruction. This is specialized a bit to avoid inserting
4456/// casts that are known to not do anything...
4457///
4458Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4459 Instruction *InsertBefore) {
4460 if (V->getType() == DestTy) return V;
4461 if (Constant *C = dyn_cast<Constant>(V))
4462 return ConstantExpr::getCast(C, DestTy);
4463
4464 CastInst *CI = new CastInst(V, DestTy, V->getName());
4465 InsertNewInstBefore(CI, *InsertBefore);
4466 return CI;
4467}
Chris Lattner48a44f72002-05-02 17:06:02 +00004468
Chris Lattner8f663e82005-10-29 04:36:15 +00004469/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4470/// expression. If so, decompose it, returning some value X, such that Val is
4471/// X*Scale+Offset.
4472///
4473static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4474 unsigned &Offset) {
4475 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4476 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4477 Offset = CI->getValue();
4478 Scale = 1;
4479 return ConstantUInt::get(Type::UIntTy, 0);
4480 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4481 if (I->getNumOperands() == 2) {
4482 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4483 if (I->getOpcode() == Instruction::Shl) {
4484 // This is a value scaled by '1 << the shift amt'.
4485 Scale = 1U << CUI->getValue();
4486 Offset = 0;
4487 return I->getOperand(0);
4488 } else if (I->getOpcode() == Instruction::Mul) {
4489 // This value is scaled by 'CUI'.
4490 Scale = CUI->getValue();
4491 Offset = 0;
4492 return I->getOperand(0);
4493 } else if (I->getOpcode() == Instruction::Add) {
4494 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4495 // divisible by C2.
4496 unsigned SubScale;
4497 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4498 Offset);
4499 Offset += CUI->getValue();
4500 if (SubScale > 1 && (Offset % SubScale == 0)) {
4501 Scale = SubScale;
4502 return SubVal;
4503 }
4504 }
4505 }
4506 }
4507 }
4508
4509 // Otherwise, we can't look past this.
4510 Scale = 1;
4511 Offset = 0;
4512 return Val;
4513}
4514
4515
Chris Lattner216be912005-10-24 06:03:58 +00004516/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4517/// try to eliminate the cast by moving the type information into the alloc.
4518Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4519 AllocationInst &AI) {
4520 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004521 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004522
Chris Lattnerac87beb2005-10-24 06:22:12 +00004523 // Remove any uses of AI that are dead.
4524 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4525 std::vector<Instruction*> DeadUsers;
4526 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4527 Instruction *User = cast<Instruction>(*UI++);
4528 if (isInstructionTriviallyDead(User)) {
4529 while (UI != E && *UI == User)
4530 ++UI; // If this instruction uses AI more than once, don't break UI.
4531
4532 // Add operands to the worklist.
4533 AddUsesToWorkList(*User);
4534 ++NumDeadInst;
4535 DEBUG(std::cerr << "IC: DCE: " << *User);
4536
4537 User->eraseFromParent();
4538 removeFromWorkList(User);
4539 }
4540 }
4541
Chris Lattner216be912005-10-24 06:03:58 +00004542 // Get the type really allocated and the type casted to.
4543 const Type *AllocElTy = AI.getAllocatedType();
4544 const Type *CastElTy = PTy->getElementType();
4545 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004546
4547 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4548 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4549 if (CastElTyAlign < AllocElTyAlign) return 0;
4550
Chris Lattner46705b22005-10-24 06:35:18 +00004551 // If the allocation has multiple uses, only promote it if we are strictly
4552 // increasing the alignment of the resultant allocation. If we keep it the
4553 // same, we open the door to infinite loops of various kinds.
4554 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4555
Chris Lattner216be912005-10-24 06:03:58 +00004556 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4557 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004558 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004559
Chris Lattner8270c332005-10-29 03:19:53 +00004560 // See if we can satisfy the modulus by pulling a scale out of the array
4561 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004562 unsigned ArraySizeScale, ArrayOffset;
4563 Value *NumElements = // See if the array size is a decomposable linear expr.
4564 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4565
Chris Lattner8270c332005-10-29 03:19:53 +00004566 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4567 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004568 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4569 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004570
Chris Lattner8270c332005-10-29 03:19:53 +00004571 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4572 Value *Amt = 0;
4573 if (Scale == 1) {
4574 Amt = NumElements;
4575 } else {
4576 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4577 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4578 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4579 else if (Scale != 1) {
4580 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4581 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004582 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004583 }
4584
Chris Lattner8f663e82005-10-29 04:36:15 +00004585 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4586 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4587 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4588 Amt = InsertNewInstBefore(Tmp, AI);
4589 }
4590
Chris Lattner216be912005-10-24 06:03:58 +00004591 std::string Name = AI.getName(); AI.setName("");
4592 AllocationInst *New;
4593 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004594 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004595 else
Nate Begeman848622f2005-11-05 09:21:28 +00004596 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004597 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004598
4599 // If the allocation has multiple uses, insert a cast and change all things
4600 // that used it to use the new cast. This will also hack on CI, but it will
4601 // die soon.
4602 if (!AI.hasOneUse()) {
4603 AddUsesToWorkList(AI);
4604 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4605 InsertNewInstBefore(NewCast, AI);
4606 AI.replaceAllUsesWith(NewCast);
4607 }
Chris Lattner216be912005-10-24 06:03:58 +00004608 return ReplaceInstUsesWith(CI, New);
4609}
4610
4611
Chris Lattner48a44f72002-05-02 17:06:02 +00004612// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004613//
Chris Lattner113f4f42002-06-25 16:13:24 +00004614Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004615 Value *Src = CI.getOperand(0);
4616
Chris Lattner48a44f72002-05-02 17:06:02 +00004617 // If the user is casting a value to the same type, eliminate this cast
4618 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00004619 if (CI.getType() == Src->getType())
4620 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00004621
Chris Lattner81a7a232004-10-16 18:11:37 +00004622 if (isa<UndefValue>(Src)) // cast undef -> undef
4623 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4624
Chris Lattner48a44f72002-05-02 17:06:02 +00004625 // If casting the result of another cast instruction, try to eliminate this
4626 // one!
4627 //
Chris Lattner86102b82005-01-01 16:22:27 +00004628 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4629 Value *A = CSrc->getOperand(0);
4630 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4631 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00004632 // This instruction now refers directly to the cast's src operand. This
4633 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00004634 CI.setOperand(0, CSrc->getOperand(0));
4635 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00004636 }
4637
Chris Lattner650b6da2002-08-02 20:00:25 +00004638 // If this is an A->B->A cast, and we are dealing with integral types, try
4639 // to convert this into a logical 'and' instruction.
4640 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00004641 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00004642 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00004643 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004644 CSrc->getType()->getPrimitiveSizeInBits() <
4645 CI.getType()->getPrimitiveSizeInBits()&&
4646 A->getType()->getPrimitiveSizeInBits() ==
4647 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00004648 assert(CSrc->getType() != Type::ULongTy &&
4649 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00004650 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00004651 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4652 AndValue);
4653 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4654 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4655 if (And->getType() != CI.getType()) {
4656 And->setName(CSrc->getName()+".mask");
4657 InsertNewInstBefore(And, CI);
4658 And = new CastInst(And, CI.getType());
4659 }
4660 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00004661 }
4662 }
Chris Lattner2590e512006-02-07 06:56:34 +00004663
Chris Lattner03841652004-05-25 04:29:21 +00004664 // If this is a cast to bool, turn it into the appropriate setne instruction.
4665 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004666 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00004667 Constant::getNullValue(CI.getOperand(0)->getType()));
4668
Chris Lattner2590e512006-02-07 06:56:34 +00004669 // See if we can simplify any instructions used by the LHS whose sole
4670 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00004671 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4672 uint64_t KnownZero, KnownOne;
4673 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4674 KnownZero, KnownOne))
4675 return &CI;
4676 }
Chris Lattner2590e512006-02-07 06:56:34 +00004677
Chris Lattnerd0d51602003-06-21 23:12:02 +00004678 // If casting the result of a getelementptr instruction with no offset, turn
4679 // this into a cast of the original pointer!
4680 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00004681 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00004682 bool AllZeroOperands = true;
4683 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4684 if (!isa<Constant>(GEP->getOperand(i)) ||
4685 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4686 AllZeroOperands = false;
4687 break;
4688 }
4689 if (AllZeroOperands) {
4690 CI.setOperand(0, GEP->getOperand(0));
4691 return &CI;
4692 }
4693 }
4694
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004695 // If we are casting a malloc or alloca to a pointer to a type of the same
4696 // size, rewrite the allocation instruction to allocate the "right" type.
4697 //
4698 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00004699 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4700 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004701
Chris Lattner86102b82005-01-01 16:22:27 +00004702 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4703 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4704 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004705 if (isa<PHINode>(Src))
4706 if (Instruction *NV = FoldOpIntoPhi(CI))
4707 return NV;
4708
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004709 // If the source value is an instruction with only this use, we can attempt to
4710 // propagate the cast into the instruction. Also, only handle integral types
4711 // for now.
4712 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004713 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004714 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4715 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004716 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4717 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004718
4719 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4720 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4721
4722 switch (SrcI->getOpcode()) {
4723 case Instruction::Add:
4724 case Instruction::Mul:
4725 case Instruction::And:
4726 case Instruction::Or:
4727 case Instruction::Xor:
4728 // If we are discarding information, or just changing the sign, rewrite.
4729 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4730 // Don't insert two casts if they cannot be eliminated. We allow two
4731 // casts to be inserted if the sizes are the same. This could only be
4732 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004733 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4734 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004735 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4736 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4737 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4738 ->getOpcode(), Op0c, Op1c);
4739 }
4740 }
Chris Lattner72086162005-05-06 02:07:39 +00004741
4742 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4743 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4744 Op1 == ConstantBool::True &&
4745 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4746 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4747 return BinaryOperator::createXor(New,
4748 ConstantInt::get(CI.getType(), 1));
4749 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004750 break;
4751 case Instruction::Shl:
4752 // Allow changing the sign of the source operand. Do not allow changing
4753 // the size of the shift, UNLESS the shift amount is a constant. We
4754 // mush not change variable sized shifts to a smaller size, because it
4755 // is undefined to shift more bits out than exist in the value.
4756 if (DestBitSize == SrcBitSize ||
4757 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4758 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4759 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4760 }
4761 break;
Chris Lattner87380412005-05-06 04:18:52 +00004762 case Instruction::Shr:
4763 // If this is a signed shr, and if all bits shifted in are about to be
4764 // truncated off, turn it into an unsigned shr to allow greater
4765 // simplifications.
4766 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4767 isa<ConstantInt>(Op1)) {
4768 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4769 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4770 // Convert to unsigned.
4771 Value *N1 = InsertOperandCastBefore(Op0,
4772 Op0->getType()->getUnsignedVersion(), &CI);
4773 // Insert the new shift, which is now unsigned.
4774 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4775 Op1, Src->getName()), CI);
4776 return new CastInst(N1, CI.getType());
4777 }
4778 }
4779 break;
4780
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004781 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00004782 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004783 // 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.
Chris Lattner809dfac2005-05-04 19:10:26 +00004786 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004787 uint64_t Op1CV = Op1C->getZExtValue();
4788 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4789 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4790 // cast (X == 1) to int --> X iff X has only the low bit set.
4791 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4792 // cast (X != 0) to int --> X iff X has only the low bit set.
4793 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4794 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4795 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4796 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4797 // If Op1C some other power of two, convert:
4798 uint64_t KnownZero, KnownOne;
4799 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4800 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4801
4802 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4803 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4804 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4805 // (X&4) == 2 --> false
4806 // (X&4) != 2 --> true
4807 return ReplaceInstUsesWith(CI, ConstantBool::get(isSetNE));
4808 }
4809
4810 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4811 Value *In = Op0;
4812 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004813 // Perform an unsigned shr by shiftamt. Convert input to
4814 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00004815 if (In->getType()->isSigned())
4816 In = InsertNewInstBefore(new CastInst(In,
4817 In->getType()->getUnsignedVersion(), In->getName()),CI);
4818 // Insert the shift to put the result in the low bit.
4819 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004820 ConstantInt::get(Type::UByteTy, ShiftAmt),
4821 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004822 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004823
4824 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4825 Constant *One = ConstantInt::get(In->getType(), 1);
4826 In = BinaryOperator::createXor(In, One, "tmp");
4827 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004828 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00004829
4830 if (CI.getType() == In->getType())
4831 return ReplaceInstUsesWith(CI, In);
4832 else
4833 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004834 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004835 }
4836 }
4837 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004838 }
4839 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004840
Chris Lattner260ab202002-04-18 17:39:14 +00004841 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004842}
4843
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004844/// GetSelectFoldableOperands - We want to turn code that looks like this:
4845/// %C = or %A, %B
4846/// %D = select %cond, %C, %A
4847/// into:
4848/// %C = select %cond, %B, 0
4849/// %D = or %A, %C
4850///
4851/// Assuming that the specified instruction is an operand to the select, return
4852/// a bitmask indicating which operands of this instruction are foldable if they
4853/// equal the other incoming value of the select.
4854///
4855static unsigned GetSelectFoldableOperands(Instruction *I) {
4856 switch (I->getOpcode()) {
4857 case Instruction::Add:
4858 case Instruction::Mul:
4859 case Instruction::And:
4860 case Instruction::Or:
4861 case Instruction::Xor:
4862 return 3; // Can fold through either operand.
4863 case Instruction::Sub: // Can only fold on the amount subtracted.
4864 case Instruction::Shl: // Can only fold on the shift amount.
4865 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004866 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004867 default:
4868 return 0; // Cannot fold
4869 }
4870}
4871
4872/// GetSelectFoldableConstant - For the same transformation as the previous
4873/// function, return the identity constant that goes into the select.
4874static Constant *GetSelectFoldableConstant(Instruction *I) {
4875 switch (I->getOpcode()) {
4876 default: assert(0 && "This cannot happen!"); abort();
4877 case Instruction::Add:
4878 case Instruction::Sub:
4879 case Instruction::Or:
4880 case Instruction::Xor:
4881 return Constant::getNullValue(I->getType());
4882 case Instruction::Shl:
4883 case Instruction::Shr:
4884 return Constant::getNullValue(Type::UByteTy);
4885 case Instruction::And:
4886 return ConstantInt::getAllOnesValue(I->getType());
4887 case Instruction::Mul:
4888 return ConstantInt::get(I->getType(), 1);
4889 }
4890}
4891
Chris Lattner411336f2005-01-19 21:50:18 +00004892/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4893/// have the same opcode and only one use each. Try to simplify this.
4894Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4895 Instruction *FI) {
4896 if (TI->getNumOperands() == 1) {
4897 // If this is a non-volatile load or a cast from the same type,
4898 // merge.
4899 if (TI->getOpcode() == Instruction::Cast) {
4900 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4901 return 0;
4902 } else {
4903 return 0; // unknown unary op.
4904 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004905
Chris Lattner411336f2005-01-19 21:50:18 +00004906 // Fold this by inserting a select from the input values.
4907 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4908 FI->getOperand(0), SI.getName()+".v");
4909 InsertNewInstBefore(NewSI, SI);
4910 return new CastInst(NewSI, TI->getType());
4911 }
4912
4913 // Only handle binary operators here.
4914 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4915 return 0;
4916
4917 // Figure out if the operations have any operands in common.
4918 Value *MatchOp, *OtherOpT, *OtherOpF;
4919 bool MatchIsOpZero;
4920 if (TI->getOperand(0) == FI->getOperand(0)) {
4921 MatchOp = TI->getOperand(0);
4922 OtherOpT = TI->getOperand(1);
4923 OtherOpF = FI->getOperand(1);
4924 MatchIsOpZero = true;
4925 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4926 MatchOp = TI->getOperand(1);
4927 OtherOpT = TI->getOperand(0);
4928 OtherOpF = FI->getOperand(0);
4929 MatchIsOpZero = false;
4930 } else if (!TI->isCommutative()) {
4931 return 0;
4932 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4933 MatchOp = TI->getOperand(0);
4934 OtherOpT = TI->getOperand(1);
4935 OtherOpF = FI->getOperand(0);
4936 MatchIsOpZero = true;
4937 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4938 MatchOp = TI->getOperand(1);
4939 OtherOpT = TI->getOperand(0);
4940 OtherOpF = FI->getOperand(1);
4941 MatchIsOpZero = true;
4942 } else {
4943 return 0;
4944 }
4945
4946 // If we reach here, they do have operations in common.
4947 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4948 OtherOpF, SI.getName()+".v");
4949 InsertNewInstBefore(NewSI, SI);
4950
4951 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4952 if (MatchIsOpZero)
4953 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4954 else
4955 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4956 } else {
4957 if (MatchIsOpZero)
4958 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4959 else
4960 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4961 }
4962}
4963
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004964Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004965 Value *CondVal = SI.getCondition();
4966 Value *TrueVal = SI.getTrueValue();
4967 Value *FalseVal = SI.getFalseValue();
4968
4969 // select true, X, Y -> X
4970 // select false, X, Y -> Y
4971 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004972 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004973 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004974 else {
4975 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004976 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004977 }
Chris Lattner533bc492004-03-30 19:37:13 +00004978
4979 // select C, X, X -> X
4980 if (TrueVal == FalseVal)
4981 return ReplaceInstUsesWith(SI, TrueVal);
4982
Chris Lattner81a7a232004-10-16 18:11:37 +00004983 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4984 return ReplaceInstUsesWith(SI, FalseVal);
4985 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4986 return ReplaceInstUsesWith(SI, TrueVal);
4987 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4988 if (isa<Constant>(TrueVal))
4989 return ReplaceInstUsesWith(SI, TrueVal);
4990 else
4991 return ReplaceInstUsesWith(SI, FalseVal);
4992 }
4993
Chris Lattner1c631e82004-04-08 04:43:23 +00004994 if (SI.getType() == Type::BoolTy)
4995 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4996 if (C == ConstantBool::True) {
4997 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004998 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004999 } else {
5000 // Change: A = select B, false, C --> A = and !B, C
5001 Value *NotCond =
5002 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5003 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005004 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005005 }
5006 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5007 if (C == ConstantBool::False) {
5008 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005009 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005010 } else {
5011 // Change: A = select B, C, true --> A = or !B, C
5012 Value *NotCond =
5013 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5014 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005015 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005016 }
5017 }
5018
Chris Lattner183b3362004-04-09 19:05:30 +00005019 // Selecting between two integer constants?
5020 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5021 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5022 // select C, 1, 0 -> cast C to int
5023 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5024 return new CastInst(CondVal, SI.getType());
5025 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5026 // select C, 0, 1 -> cast !C to int
5027 Value *NotCond =
5028 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005029 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005030 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005031 }
Chris Lattner35167c32004-06-09 07:59:58 +00005032
5033 // If one of the constants is zero (we know they can't both be) and we
5034 // have a setcc instruction with zero, and we have an 'and' with the
5035 // non-constant value, eliminate this whole mess. This corresponds to
5036 // cases like this: ((X & 27) ? 27 : 0)
5037 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5038 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5039 if ((IC->getOpcode() == Instruction::SetEQ ||
5040 IC->getOpcode() == Instruction::SetNE) &&
5041 isa<ConstantInt>(IC->getOperand(1)) &&
5042 cast<Constant>(IC->getOperand(1))->isNullValue())
5043 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5044 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005045 isa<ConstantInt>(ICA->getOperand(1)) &&
5046 (ICA->getOperand(1) == TrueValC ||
5047 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005048 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5049 // Okay, now we know that everything is set up, we just don't
5050 // know whether we have a setne or seteq and whether the true or
5051 // false val is the zero.
5052 bool ShouldNotVal = !TrueValC->isNullValue();
5053 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5054 Value *V = ICA;
5055 if (ShouldNotVal)
5056 V = InsertNewInstBefore(BinaryOperator::create(
5057 Instruction::Xor, V, ICA->getOperand(1)), SI);
5058 return ReplaceInstUsesWith(SI, V);
5059 }
Chris Lattner533bc492004-03-30 19:37:13 +00005060 }
Chris Lattner623fba12004-04-10 22:21:27 +00005061
5062 // See if we are selecting two values based on a comparison of the two values.
5063 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5064 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5065 // Transform (X == Y) ? X : Y -> Y
5066 if (SCI->getOpcode() == Instruction::SetEQ)
5067 return ReplaceInstUsesWith(SI, FalseVal);
5068 // Transform (X != Y) ? X : Y -> X
5069 if (SCI->getOpcode() == Instruction::SetNE)
5070 return ReplaceInstUsesWith(SI, TrueVal);
5071 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5072
5073 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5074 // Transform (X == Y) ? Y : X -> X
5075 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005076 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005077 // Transform (X != Y) ? Y : X -> Y
5078 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005079 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005080 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5081 }
5082 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005083
Chris Lattnera04c9042005-01-13 22:52:24 +00005084 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5085 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5086 if (TI->hasOneUse() && FI->hasOneUse()) {
5087 bool isInverse = false;
5088 Instruction *AddOp = 0, *SubOp = 0;
5089
Chris Lattner411336f2005-01-19 21:50:18 +00005090 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5091 if (TI->getOpcode() == FI->getOpcode())
5092 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5093 return IV;
5094
5095 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5096 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005097 if (TI->getOpcode() == Instruction::Sub &&
5098 FI->getOpcode() == Instruction::Add) {
5099 AddOp = FI; SubOp = TI;
5100 } else if (FI->getOpcode() == Instruction::Sub &&
5101 TI->getOpcode() == Instruction::Add) {
5102 AddOp = TI; SubOp = FI;
5103 }
5104
5105 if (AddOp) {
5106 Value *OtherAddOp = 0;
5107 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5108 OtherAddOp = AddOp->getOperand(1);
5109 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5110 OtherAddOp = AddOp->getOperand(0);
5111 }
5112
5113 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005114 // So at this point we know we have (Y -> OtherAddOp):
5115 // select C, (add X, Y), (sub X, Z)
5116 Value *NegVal; // Compute -Z
5117 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5118 NegVal = ConstantExpr::getNeg(C);
5119 } else {
5120 NegVal = InsertNewInstBefore(
5121 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005122 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005123
5124 Value *NewTrueOp = OtherAddOp;
5125 Value *NewFalseOp = NegVal;
5126 if (AddOp != TI)
5127 std::swap(NewTrueOp, NewFalseOp);
5128 Instruction *NewSel =
5129 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5130
5131 NewSel = InsertNewInstBefore(NewSel, SI);
5132 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005133 }
5134 }
5135 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005136
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005137 // See if we can fold the select into one of our operands.
5138 if (SI.getType()->isInteger()) {
5139 // See the comment above GetSelectFoldableOperands for a description of the
5140 // transformation we are doing here.
5141 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5142 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5143 !isa<Constant>(FalseVal))
5144 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5145 unsigned OpToFold = 0;
5146 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5147 OpToFold = 1;
5148 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5149 OpToFold = 2;
5150 }
5151
5152 if (OpToFold) {
5153 Constant *C = GetSelectFoldableConstant(TVI);
5154 std::string Name = TVI->getName(); TVI->setName("");
5155 Instruction *NewSel =
5156 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5157 Name);
5158 InsertNewInstBefore(NewSel, SI);
5159 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5160 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5161 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5162 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5163 else {
5164 assert(0 && "Unknown instruction!!");
5165 }
5166 }
5167 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005168
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005169 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5170 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5171 !isa<Constant>(TrueVal))
5172 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5173 unsigned OpToFold = 0;
5174 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5175 OpToFold = 1;
5176 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5177 OpToFold = 2;
5178 }
5179
5180 if (OpToFold) {
5181 Constant *C = GetSelectFoldableConstant(FVI);
5182 std::string Name = FVI->getName(); FVI->setName("");
5183 Instruction *NewSel =
5184 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5185 Name);
5186 InsertNewInstBefore(NewSel, SI);
5187 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5188 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5189 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5190 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5191 else {
5192 assert(0 && "Unknown instruction!!");
5193 }
5194 }
5195 }
5196 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005197
5198 if (BinaryOperator::isNot(CondVal)) {
5199 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5200 SI.setOperand(1, FalseVal);
5201 SI.setOperand(2, TrueVal);
5202 return &SI;
5203 }
5204
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005205 return 0;
5206}
5207
5208
Chris Lattnerc66b2232006-01-13 20:11:04 +00005209/// visitCallInst - CallInst simplification. This mostly only handles folding
5210/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5211/// the heavy lifting.
5212///
Chris Lattner970c33a2003-06-19 17:00:31 +00005213Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005214 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5215 if (!II) return visitCallSite(&CI);
5216
Chris Lattner51ea1272004-02-28 05:22:00 +00005217 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5218 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005219 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005220 bool Changed = false;
5221
5222 // memmove/cpy/set of zero bytes is a noop.
5223 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5224 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5225
5226 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005227
Chris Lattner00648e12004-10-12 04:52:52 +00005228 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5229 if (CI->getRawValue() == 1) {
5230 // Replace the instruction with just byte operations. We would
5231 // transform other cases to loads/stores, but we don't know if
5232 // alignment is sufficient.
5233 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005234 }
5235
Chris Lattner00648e12004-10-12 04:52:52 +00005236 // If we have a memmove and the source operation is a constant global,
5237 // then the source and dest pointers can't alias, so we can change this
5238 // into a call to memcpy.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005239 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
Chris Lattner00648e12004-10-12 04:52:52 +00005240 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5241 if (GVSrc->isConstant()) {
5242 Module *M = CI.getParent()->getParent()->getParent();
5243 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
5244 CI.getCalledFunction()->getFunctionType());
5245 CI.setOperand(0, MemCpy);
5246 Changed = true;
5247 }
5248
Chris Lattnerc66b2232006-01-13 20:11:04 +00005249 if (Changed) return II;
5250 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
Chris Lattner95307542004-11-18 21:41:39 +00005251 // If this stoppoint is at the same source location as the previous
5252 // stoppoint in the chain, it is not needed.
5253 if (DbgStopPointInst *PrevSPI =
5254 dyn_cast<DbgStopPointInst>(SPI->getChain()))
5255 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
5256 SPI->getColNo() == PrevSPI->getColNo()) {
5257 SPI->replaceAllUsesWith(PrevSPI);
5258 return EraseInstFromFunction(CI);
5259 }
Chris Lattner503221f2006-01-13 21:28:09 +00005260 } else {
5261 switch (II->getIntrinsicID()) {
5262 default: break;
5263 case Intrinsic::stackrestore: {
5264 // If the save is right next to the restore, remove the restore. This can
5265 // happen when variable allocas are DCE'd.
5266 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5267 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5268 BasicBlock::iterator BI = SS;
5269 if (&*++BI == II)
5270 return EraseInstFromFunction(CI);
5271 }
5272 }
5273
5274 // If the stack restore is in a return/unwind block and if there are no
5275 // allocas or calls between the restore and the return, nuke the restore.
5276 TerminatorInst *TI = II->getParent()->getTerminator();
5277 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5278 BasicBlock::iterator BI = II;
5279 bool CannotRemove = false;
5280 for (++BI; &*BI != TI; ++BI) {
5281 if (isa<AllocaInst>(BI) ||
5282 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5283 CannotRemove = true;
5284 break;
5285 }
5286 }
5287 if (!CannotRemove)
5288 return EraseInstFromFunction(CI);
5289 }
5290 break;
5291 }
5292 }
Chris Lattner00648e12004-10-12 04:52:52 +00005293 }
5294
Chris Lattnerc66b2232006-01-13 20:11:04 +00005295 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005296}
5297
5298// InvokeInst simplification
5299//
5300Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005301 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005302}
5303
Chris Lattneraec3d942003-10-07 22:32:43 +00005304// visitCallSite - Improvements for call and invoke instructions.
5305//
5306Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005307 bool Changed = false;
5308
5309 // If the callee is a constexpr cast of a function, attempt to move the cast
5310 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005311 if (transformConstExprCastCall(CS)) return 0;
5312
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005313 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005314
Chris Lattner61d9d812005-05-13 07:09:09 +00005315 if (Function *CalleeF = dyn_cast<Function>(Callee))
5316 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5317 Instruction *OldCall = CS.getInstruction();
5318 // If the call and callee calling conventions don't match, this call must
5319 // be unreachable, as the call is undefined.
5320 new StoreInst(ConstantBool::True,
5321 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5322 if (!OldCall->use_empty())
5323 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5324 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5325 return EraseInstFromFunction(*OldCall);
5326 return 0;
5327 }
5328
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005329 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5330 // This instruction is not reachable, just remove it. We insert a store to
5331 // undef so that we know that this code is not reachable, despite the fact
5332 // that we can't modify the CFG here.
5333 new StoreInst(ConstantBool::True,
5334 UndefValue::get(PointerType::get(Type::BoolTy)),
5335 CS.getInstruction());
5336
5337 if (!CS.getInstruction()->use_empty())
5338 CS.getInstruction()->
5339 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5340
5341 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5342 // Don't break the CFG, insert a dummy cond branch.
5343 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5344 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005345 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005346 return EraseInstFromFunction(*CS.getInstruction());
5347 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005348
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005349 const PointerType *PTy = cast<PointerType>(Callee->getType());
5350 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5351 if (FTy->isVarArg()) {
5352 // See if we can optimize any arguments passed through the varargs area of
5353 // the call.
5354 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5355 E = CS.arg_end(); I != E; ++I)
5356 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5357 // If this cast does not effect the value passed through the varargs
5358 // area, we can eliminate the use of the cast.
5359 Value *Op = CI->getOperand(0);
5360 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5361 *I = Op;
5362 Changed = true;
5363 }
5364 }
5365 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005366
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005367 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00005368}
5369
Chris Lattner970c33a2003-06-19 17:00:31 +00005370// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5371// attempt to move the cast to the arguments of the call/invoke.
5372//
5373bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5374 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5375 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00005376 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00005377 return false;
Reid Spencer87436872004-07-18 00:38:32 +00005378 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00005379 Instruction *Caller = CS.getInstruction();
5380
5381 // Okay, this is a cast from a function to a different type. Unless doing so
5382 // would cause a type conversion of one of our arguments, change this call to
5383 // be a direct call with arguments casted to the appropriate types.
5384 //
5385 const FunctionType *FT = Callee->getFunctionType();
5386 const Type *OldRetTy = Caller->getType();
5387
Chris Lattner1f7942f2004-01-14 06:06:08 +00005388 // Check to see if we are changing the return type...
5389 if (OldRetTy != FT->getReturnType()) {
5390 if (Callee->isExternal() &&
5391 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5392 !Caller->use_empty())
5393 return false; // Cannot transform this return value...
5394
5395 // If the callsite is an invoke instruction, and the return value is used by
5396 // a PHI node in a successor, we cannot change the return type of the call
5397 // because there is no place to put the cast instruction (without breaking
5398 // the critical edge). Bail out in this case.
5399 if (!Caller->use_empty())
5400 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5401 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5402 UI != E; ++UI)
5403 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5404 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005405 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00005406 return false;
5407 }
Chris Lattner970c33a2003-06-19 17:00:31 +00005408
5409 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5410 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005411
Chris Lattner970c33a2003-06-19 17:00:31 +00005412 CallSite::arg_iterator AI = CS.arg_begin();
5413 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5414 const Type *ParamTy = FT->getParamType(i);
5415 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005416 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00005417 }
5418
5419 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5420 Callee->isExternal())
5421 return false; // Do not delete arguments unless we have a function body...
5422
5423 // Okay, we decided that this is a safe thing to do: go ahead and start
5424 // inserting cast instructions as necessary...
5425 std::vector<Value*> Args;
5426 Args.reserve(NumActualArgs);
5427
5428 AI = CS.arg_begin();
5429 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5430 const Type *ParamTy = FT->getParamType(i);
5431 if ((*AI)->getType() == ParamTy) {
5432 Args.push_back(*AI);
5433 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00005434 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5435 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00005436 }
5437 }
5438
5439 // If the function takes more arguments than the call was taking, add them
5440 // now...
5441 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5442 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5443
5444 // If we are removing arguments to the function, emit an obnoxious warning...
5445 if (FT->getNumParams() < NumActualArgs)
5446 if (!FT->isVarArg()) {
5447 std::cerr << "WARNING: While resolving call to function '"
5448 << Callee->getName() << "' arguments were dropped!\n";
5449 } else {
5450 // Add all of the arguments in their promoted form to the arg list...
5451 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5452 const Type *PTy = getPromotedType((*AI)->getType());
5453 if (PTy != (*AI)->getType()) {
5454 // Must promote to pass through va_arg area!
5455 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5456 InsertNewInstBefore(Cast, *Caller);
5457 Args.push_back(Cast);
5458 } else {
5459 Args.push_back(*AI);
5460 }
5461 }
5462 }
5463
5464 if (FT->getReturnType() == Type::VoidTy)
5465 Caller->setName(""); // Void type should not have a name...
5466
5467 Instruction *NC;
5468 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00005469 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00005470 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00005471 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005472 } else {
5473 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00005474 if (cast<CallInst>(Caller)->isTailCall())
5475 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00005476 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00005477 }
5478
5479 // Insert a cast of the return type as necessary...
5480 Value *NV = NC;
5481 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5482 if (NV->getType() != Type::VoidTy) {
5483 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00005484
5485 // If this is an invoke instruction, we should insert it after the first
5486 // non-phi, instruction in the normal successor block.
5487 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5488 BasicBlock::iterator I = II->getNormalDest()->begin();
5489 while (isa<PHINode>(I)) ++I;
5490 InsertNewInstBefore(NC, *I);
5491 } else {
5492 // Otherwise, it's a call, just insert cast right after the call instr
5493 InsertNewInstBefore(NC, *Caller);
5494 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005495 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00005496 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00005497 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00005498 }
5499 }
5500
5501 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5502 Caller->replaceAllUsesWith(NV);
5503 Caller->getParent()->getInstList().erase(Caller);
5504 removeFromWorkList(Caller);
5505 return true;
5506}
5507
5508
Chris Lattner7515cab2004-11-14 19:13:23 +00005509// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5510// operator and they all are only used by the PHI, PHI together their
5511// inputs, and do the operation once, to the result of the PHI.
5512Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5513 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5514
5515 // Scan the instruction, looking for input operations that can be folded away.
5516 // If all input operands to the phi are the same instruction (e.g. a cast from
5517 // the same type or "+42") we can pull the operation through the PHI, reducing
5518 // code size and simplifying code.
5519 Constant *ConstantOp = 0;
5520 const Type *CastSrcTy = 0;
5521 if (isa<CastInst>(FirstInst)) {
5522 CastSrcTy = FirstInst->getOperand(0)->getType();
5523 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5524 // Can fold binop or shift if the RHS is a constant.
5525 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5526 if (ConstantOp == 0) return 0;
5527 } else {
5528 return 0; // Cannot fold this operation.
5529 }
5530
5531 // Check to see if all arguments are the same operation.
5532 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5533 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5534 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5535 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5536 return 0;
5537 if (CastSrcTy) {
5538 if (I->getOperand(0)->getType() != CastSrcTy)
5539 return 0; // Cast operation must match.
5540 } else if (I->getOperand(1) != ConstantOp) {
5541 return 0;
5542 }
5543 }
5544
5545 // Okay, they are all the same operation. Create a new PHI node of the
5546 // correct type, and PHI together all of the LHS's of the instructions.
5547 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5548 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00005549 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00005550
5551 Value *InVal = FirstInst->getOperand(0);
5552 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00005553
5554 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00005555 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5556 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5557 if (NewInVal != InVal)
5558 InVal = 0;
5559 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5560 }
5561
5562 Value *PhiVal;
5563 if (InVal) {
5564 // The new PHI unions all of the same values together. This is really
5565 // common, so we handle it intelligently here for compile-time speed.
5566 PhiVal = InVal;
5567 delete NewPN;
5568 } else {
5569 InsertNewInstBefore(NewPN, PN);
5570 PhiVal = NewPN;
5571 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005572
Chris Lattner7515cab2004-11-14 19:13:23 +00005573 // Insert and return the new operation.
5574 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005575 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00005576 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00005577 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005578 else
5579 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00005580 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00005581}
Chris Lattner48a44f72002-05-02 17:06:02 +00005582
Chris Lattner71536432005-01-17 05:10:15 +00005583/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5584/// that is dead.
5585static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5586 if (PN->use_empty()) return true;
5587 if (!PN->hasOneUse()) return false;
5588
5589 // Remember this node, and if we find the cycle, return.
5590 if (!PotentiallyDeadPHIs.insert(PN).second)
5591 return true;
5592
5593 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5594 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005595
Chris Lattner71536432005-01-17 05:10:15 +00005596 return false;
5597}
5598
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005599// PHINode simplification
5600//
Chris Lattner113f4f42002-06-25 16:13:24 +00005601Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00005602 if (Value *V = PN.hasConstantValue())
5603 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00005604
5605 // If the only user of this instruction is a cast instruction, and all of the
5606 // incoming values are constants, change this PHI to merge together the casted
5607 // constants.
5608 if (PN.hasOneUse())
5609 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5610 if (CI->getType() != PN.getType()) { // noop casts will be folded
5611 bool AllConstant = true;
5612 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5613 if (!isa<Constant>(PN.getIncomingValue(i))) {
5614 AllConstant = false;
5615 break;
5616 }
5617 if (AllConstant) {
5618 // Make a new PHI with all casted values.
5619 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5620 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5621 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5622 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5623 PN.getIncomingBlock(i));
5624 }
5625
5626 // Update the cast instruction.
5627 CI->setOperand(0, New);
5628 WorkList.push_back(CI); // revisit the cast instruction to fold.
5629 WorkList.push_back(New); // Make sure to revisit the new Phi
5630 return &PN; // PN is now dead!
5631 }
5632 }
Chris Lattner7515cab2004-11-14 19:13:23 +00005633
5634 // If all PHI operands are the same operation, pull them through the PHI,
5635 // reducing code size.
5636 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5637 PN.getIncomingValue(0)->hasOneUse())
5638 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5639 return Result;
5640
Chris Lattner71536432005-01-17 05:10:15 +00005641 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5642 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5643 // PHI)... break the cycle.
5644 if (PN.hasOneUse())
5645 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5646 std::set<PHINode*> PotentiallyDeadPHIs;
5647 PotentiallyDeadPHIs.insert(&PN);
5648 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5649 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5650 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005651
Chris Lattner91daeb52003-12-19 05:58:40 +00005652 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00005653}
5654
Chris Lattner69193f92004-04-05 01:30:19 +00005655static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5656 Instruction *InsertPoint,
5657 InstCombiner *IC) {
5658 unsigned PS = IC->getTargetData().getPointerSize();
5659 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00005660 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5661 // We must insert a cast to ensure we sign-extend.
5662 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5663 V->getName()), *InsertPoint);
5664 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5665 *InsertPoint);
5666}
5667
Chris Lattner48a44f72002-05-02 17:06:02 +00005668
Chris Lattner113f4f42002-06-25 16:13:24 +00005669Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005670 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00005671 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00005672 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005673 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00005674 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005675
Chris Lattner81a7a232004-10-16 18:11:37 +00005676 if (isa<UndefValue>(GEP.getOperand(0)))
5677 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5678
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005679 bool HasZeroPointerIndex = false;
5680 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5681 HasZeroPointerIndex = C->isNullValue();
5682
5683 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00005684 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00005685
Chris Lattner69193f92004-04-05 01:30:19 +00005686 // Eliminate unneeded casts for indices.
5687 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00005688 gep_type_iterator GTI = gep_type_begin(GEP);
5689 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5690 if (isa<SequentialType>(*GTI)) {
5691 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5692 Value *Src = CI->getOperand(0);
5693 const Type *SrcTy = Src->getType();
5694 const Type *DestTy = CI->getType();
5695 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005696 if (SrcTy->getPrimitiveSizeInBits() ==
5697 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005698 // We can always eliminate a cast from ulong or long to the other.
5699 // We can always eliminate a cast from uint to int or the other on
5700 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005701 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00005702 MadeChange = true;
5703 GEP.setOperand(i, Src);
5704 }
5705 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5706 SrcTy->getPrimitiveSize() == 4) {
5707 // We can always eliminate a cast from int to [u]long. We can
5708 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5709 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005710 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005711 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005712 MadeChange = true;
5713 GEP.setOperand(i, Src);
5714 }
Chris Lattner69193f92004-04-05 01:30:19 +00005715 }
5716 }
5717 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00005718 // If we are using a wider index than needed for this platform, shrink it
5719 // to what we need. If the incoming value needs a cast instruction,
5720 // insert it. This explicit cast can make subsequent optimizations more
5721 // obvious.
5722 Value *Op = GEP.getOperand(i);
5723 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005724 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00005725 GEP.setOperand(i, ConstantExpr::getCast(C,
5726 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00005727 MadeChange = true;
5728 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00005729 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5730 Op->getName()), GEP);
5731 GEP.setOperand(i, Op);
5732 MadeChange = true;
5733 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005734
5735 // If this is a constant idx, make sure to canonicalize it to be a signed
5736 // operand, otherwise CSE and other optimizations are pessimized.
5737 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5738 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5739 CUI->getType()->getSignedVersion()));
5740 MadeChange = true;
5741 }
Chris Lattner69193f92004-04-05 01:30:19 +00005742 }
5743 if (MadeChange) return &GEP;
5744
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005745 // Combine Indices - If the source pointer to this getelementptr instruction
5746 // is a getelementptr instruction, combine the indices of the two
5747 // getelementptr instructions into a single instruction.
5748 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005749 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005750 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005751 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005752
5753 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005754 // Note that if our source is a gep chain itself that we wait for that
5755 // chain to be resolved before we perform this transformation. This
5756 // avoids us creating a TON of code in some cases.
5757 //
5758 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5759 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5760 return 0; // Wait until our source is folded to completion.
5761
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005762 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005763
5764 // Find out whether the last index in the source GEP is a sequential idx.
5765 bool EndsWithSequential = false;
5766 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5767 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005768 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005769
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005770 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005771 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005772 // Replace: gep (gep %P, long B), long A, ...
5773 // With: T = long A+B; gep %P, T, ...
5774 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005775 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005776 if (SO1 == Constant::getNullValue(SO1->getType())) {
5777 Sum = GO1;
5778 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5779 Sum = SO1;
5780 } else {
5781 // If they aren't the same type, convert both to an integer of the
5782 // target's pointer size.
5783 if (SO1->getType() != GO1->getType()) {
5784 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5785 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5786 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5787 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5788 } else {
5789 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005790 if (SO1->getType()->getPrimitiveSize() == PS) {
5791 // Convert GO1 to SO1's type.
5792 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5793
5794 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5795 // Convert SO1 to GO1's type.
5796 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5797 } else {
5798 const Type *PT = TD->getIntPtrType();
5799 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5800 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5801 }
5802 }
5803 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005804 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5805 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5806 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005807 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5808 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005809 }
Chris Lattner69193f92004-04-05 01:30:19 +00005810 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005811
5812 // Recycle the GEP we already have if possible.
5813 if (SrcGEPOperands.size() == 2) {
5814 GEP.setOperand(0, SrcGEPOperands[0]);
5815 GEP.setOperand(1, Sum);
5816 return &GEP;
5817 } else {
5818 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5819 SrcGEPOperands.end()-1);
5820 Indices.push_back(Sum);
5821 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5822 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005823 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005824 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005825 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005826 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005827 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5828 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005829 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5830 }
5831
5832 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005833 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005834
Chris Lattner5f667a62004-05-07 22:09:22 +00005835 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005836 // GEP of global variable. If all of the indices for this GEP are
5837 // constants, we can promote this to a constexpr instead of an instruction.
5838
5839 // Scan for nonconstants...
5840 std::vector<Constant*> Indices;
5841 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5842 for (; I != E && isa<Constant>(*I); ++I)
5843 Indices.push_back(cast<Constant>(*I));
5844
5845 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005846 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005847
5848 // Replace all uses of the GEP with the new constexpr...
5849 return ReplaceInstUsesWith(GEP, CE);
5850 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005851 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5852 if (!isa<PointerType>(X->getType())) {
5853 // Not interesting. Source pointer must be a cast from pointer.
5854 } else if (HasZeroPointerIndex) {
5855 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5856 // into : GEP [10 x ubyte]* X, long 0, ...
5857 //
5858 // This occurs when the program declares an array extern like "int X[];"
5859 //
5860 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5861 const PointerType *XTy = cast<PointerType>(X->getType());
5862 if (const ArrayType *XATy =
5863 dyn_cast<ArrayType>(XTy->getElementType()))
5864 if (const ArrayType *CATy =
5865 dyn_cast<ArrayType>(CPTy->getElementType()))
5866 if (CATy->getElementType() == XATy->getElementType()) {
5867 // At this point, we know that the cast source type is a pointer
5868 // to an array of the same type as the destination pointer
5869 // array. Because the array type is never stepped over (there
5870 // is a leading zero) we can fold the cast into this GEP.
5871 GEP.setOperand(0, X);
5872 return &GEP;
5873 }
5874 } else if (GEP.getNumOperands() == 2) {
5875 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005876 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5877 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005878 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5879 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5880 if (isa<ArrayType>(SrcElTy) &&
5881 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5882 TD->getTypeSize(ResElTy)) {
5883 Value *V = InsertNewInstBefore(
5884 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5885 GEP.getOperand(1), GEP.getName()), GEP);
5886 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005887 }
Chris Lattner2a893292005-09-13 18:36:04 +00005888
5889 // Transform things like:
5890 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5891 // (where tmp = 8*tmp2) into:
5892 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5893
5894 if (isa<ArrayType>(SrcElTy) &&
5895 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5896 uint64_t ArrayEltSize =
5897 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5898
5899 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5900 // allow either a mul, shift, or constant here.
5901 Value *NewIdx = 0;
5902 ConstantInt *Scale = 0;
5903 if (ArrayEltSize == 1) {
5904 NewIdx = GEP.getOperand(1);
5905 Scale = ConstantInt::get(NewIdx->getType(), 1);
5906 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005907 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005908 Scale = CI;
5909 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5910 if (Inst->getOpcode() == Instruction::Shl &&
5911 isa<ConstantInt>(Inst->getOperand(1))) {
5912 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5913 if (Inst->getType()->isSigned())
5914 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5915 else
5916 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5917 NewIdx = Inst->getOperand(0);
5918 } else if (Inst->getOpcode() == Instruction::Mul &&
5919 isa<ConstantInt>(Inst->getOperand(1))) {
5920 Scale = cast<ConstantInt>(Inst->getOperand(1));
5921 NewIdx = Inst->getOperand(0);
5922 }
5923 }
5924
5925 // If the index will be to exactly the right offset with the scale taken
5926 // out, perform the transformation.
5927 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5928 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5929 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005930 (int64_t)C->getRawValue() /
5931 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005932 else
5933 Scale = ConstantUInt::get(Scale->getType(),
5934 Scale->getRawValue() / ArrayEltSize);
5935 if (Scale->getRawValue() != 1) {
5936 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5937 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5938 NewIdx = InsertNewInstBefore(Sc, GEP);
5939 }
5940
5941 // Insert the new GEP instruction.
5942 Instruction *Idx =
5943 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5944 NewIdx, GEP.getName());
5945 Idx = InsertNewInstBefore(Idx, GEP);
5946 return new CastInst(Idx, GEP.getType());
5947 }
5948 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005949 }
Chris Lattnerca081252001-12-14 16:52:21 +00005950 }
5951
Chris Lattnerca081252001-12-14 16:52:21 +00005952 return 0;
5953}
5954
Chris Lattner1085bdf2002-11-04 16:18:53 +00005955Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5956 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5957 if (AI.isArrayAllocation()) // Check C != 1
5958 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5959 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005960 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005961
5962 // Create and insert the replacement instruction...
5963 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00005964 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005965 else {
5966 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00005967 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005968 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005969
5970 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005971
Chris Lattner1085bdf2002-11-04 16:18:53 +00005972 // Scan to the end of the allocation instructions, to skip over a block of
5973 // allocas if possible...
5974 //
5975 BasicBlock::iterator It = New;
5976 while (isa<AllocationInst>(*It)) ++It;
5977
5978 // Now that I is pointing to the first non-allocation-inst in the block,
5979 // insert our getelementptr instruction...
5980 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005981 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5982 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5983 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005984
5985 // Now make everything use the getelementptr instead of the original
5986 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005987 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005988 } else if (isa<UndefValue>(AI.getArraySize())) {
5989 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005990 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005991
5992 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5993 // Note that we only do this for alloca's, because malloc should allocate and
5994 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005995 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005996 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005997 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5998
Chris Lattner1085bdf2002-11-04 16:18:53 +00005999 return 0;
6000}
6001
Chris Lattner8427bff2003-12-07 01:24:23 +00006002Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6003 Value *Op = FI.getOperand(0);
6004
6005 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6006 if (CastInst *CI = dyn_cast<CastInst>(Op))
6007 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6008 FI.setOperand(0, CI->getOperand(0));
6009 return &FI;
6010 }
6011
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006012 // free undef -> unreachable.
6013 if (isa<UndefValue>(Op)) {
6014 // Insert a new store to null because we cannot modify the CFG here.
6015 new StoreInst(ConstantBool::True,
6016 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6017 return EraseInstFromFunction(FI);
6018 }
6019
Chris Lattnerf3a36602004-02-28 04:57:37 +00006020 // If we have 'free null' delete the instruction. This can happen in stl code
6021 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006022 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006023 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006024
Chris Lattner8427bff2003-12-07 01:24:23 +00006025 return 0;
6026}
6027
6028
Chris Lattner72684fe2005-01-31 05:51:45 +00006029/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006030static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6031 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006032 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006033
6034 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006035 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006036 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006037
6038 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6039 // If the source is an array, the code below will not succeed. Check to
6040 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6041 // constants.
6042 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6043 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6044 if (ASrcTy->getNumElements() != 0) {
6045 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6046 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6047 SrcTy = cast<PointerType>(CastOp->getType());
6048 SrcPTy = SrcTy->getElementType();
6049 }
6050
6051 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006052 // Do not allow turning this into a load of an integer, which is then
6053 // casted to a pointer, this pessimizes pointer analysis a lot.
6054 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006055 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006056 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006057
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006058 // Okay, we are casting from one integer or pointer type to another of
6059 // the same size. Instead of casting the pointer before the load, cast
6060 // the result of the loaded value.
6061 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6062 CI->getName(),
6063 LI.isVolatile()),LI);
6064 // Now cast the result of the load.
6065 return new CastInst(NewLoad, LI.getType());
6066 }
Chris Lattner35e24772004-07-13 01:49:43 +00006067 }
6068 }
6069 return 0;
6070}
6071
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006072/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006073/// from this value cannot trap. If it is not obviously safe to load from the
6074/// specified pointer, we do a quick local scan of the basic block containing
6075/// ScanFrom, to determine if the address is already accessed.
6076static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6077 // If it is an alloca or global variable, it is always safe to load from.
6078 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6079
6080 // Otherwise, be a little bit agressive by scanning the local block where we
6081 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006082 // from/to. If so, the previous load or store would have already trapped,
6083 // so there is no harm doing an extra load (also, CSE will later eliminate
6084 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006085 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6086
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006087 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006088 --BBI;
6089
6090 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6091 if (LI->getOperand(0) == V) return true;
6092 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6093 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006094
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006095 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006096 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006097}
6098
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006099Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6100 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006101
Chris Lattnera9d84e32005-05-01 04:24:53 +00006102 // load (cast X) --> cast (load X) iff safe
6103 if (CastInst *CI = dyn_cast<CastInst>(Op))
6104 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6105 return Res;
6106
6107 // None of the following transforms are legal for volatile loads.
6108 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006109
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006110 if (&LI.getParent()->front() != &LI) {
6111 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006112 // If the instruction immediately before this is a store to the same
6113 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006114 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6115 if (SI->getOperand(1) == LI.getOperand(0))
6116 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006117 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6118 if (LIB->getOperand(0) == LI.getOperand(0))
6119 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006120 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006121
6122 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6123 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6124 isa<UndefValue>(GEPI->getOperand(0))) {
6125 // Insert a new store to null instruction before the load to indicate
6126 // that this code is not reachable. We do this instead of inserting
6127 // an unreachable instruction directly because we cannot modify the
6128 // CFG.
6129 new StoreInst(UndefValue::get(LI.getType()),
6130 Constant::getNullValue(Op->getType()), &LI);
6131 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6132 }
6133
Chris Lattner81a7a232004-10-16 18:11:37 +00006134 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006135 // load null/undef -> undef
6136 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006137 // Insert a new store to null instruction before the load to indicate that
6138 // this code is not reachable. We do this instead of inserting an
6139 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006140 new StoreInst(UndefValue::get(LI.getType()),
6141 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006142 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006143 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006144
Chris Lattner81a7a232004-10-16 18:11:37 +00006145 // Instcombine load (constant global) into the value loaded.
6146 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6147 if (GV->isConstant() && !GV->isExternal())
6148 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006149
Chris Lattner81a7a232004-10-16 18:11:37 +00006150 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6151 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6152 if (CE->getOpcode() == Instruction::GetElementPtr) {
6153 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6154 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006155 if (Constant *V =
6156 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006157 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006158 if (CE->getOperand(0)->isNullValue()) {
6159 // Insert a new store to null instruction before the load to indicate
6160 // that this code is not reachable. We do this instead of inserting
6161 // an unreachable instruction directly because we cannot modify the
6162 // CFG.
6163 new StoreInst(UndefValue::get(LI.getType()),
6164 Constant::getNullValue(Op->getType()), &LI);
6165 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6166 }
6167
Chris Lattner81a7a232004-10-16 18:11:37 +00006168 } else if (CE->getOpcode() == Instruction::Cast) {
6169 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6170 return Res;
6171 }
6172 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006173
Chris Lattnera9d84e32005-05-01 04:24:53 +00006174 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006175 // Change select and PHI nodes to select values instead of addresses: this
6176 // helps alias analysis out a lot, allows many others simplifications, and
6177 // exposes redundancy in the code.
6178 //
6179 // Note that we cannot do the transformation unless we know that the
6180 // introduced loads cannot trap! Something like this is valid as long as
6181 // the condition is always false: load (select bool %C, int* null, int* %G),
6182 // but it would not be valid if we transformed it to load from null
6183 // unconditionally.
6184 //
6185 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6186 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006187 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6188 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006189 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006190 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006191 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006192 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006193 return new SelectInst(SI->getCondition(), V1, V2);
6194 }
6195
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006196 // load (select (cond, null, P)) -> load P
6197 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6198 if (C->isNullValue()) {
6199 LI.setOperand(0, SI->getOperand(2));
6200 return &LI;
6201 }
6202
6203 // load (select (cond, P, null)) -> load P
6204 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6205 if (C->isNullValue()) {
6206 LI.setOperand(0, SI->getOperand(1));
6207 return &LI;
6208 }
6209
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006210 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6211 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006212 bool Safe = PN->getParent() == LI.getParent();
6213
6214 // Scan all of the instructions between the PHI and the load to make
6215 // sure there are no instructions that might possibly alter the value
6216 // loaded from the PHI.
6217 if (Safe) {
6218 BasicBlock::iterator I = &LI;
6219 for (--I; !isa<PHINode>(I); --I)
6220 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6221 Safe = false;
6222 break;
6223 }
6224 }
6225
6226 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006227 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006228 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006229 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006230
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006231 if (Safe) {
6232 // Create the PHI.
6233 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6234 InsertNewInstBefore(NewPN, *PN);
6235 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6236
6237 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6238 BasicBlock *BB = PN->getIncomingBlock(i);
6239 Value *&TheLoad = LoadMap[BB];
6240 if (TheLoad == 0) {
6241 Value *InVal = PN->getIncomingValue(i);
6242 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6243 InVal->getName()+".val"),
6244 *BB->getTerminator());
6245 }
6246 NewPN->addIncoming(TheLoad, BB);
6247 }
6248 return ReplaceInstUsesWith(LI, NewPN);
6249 }
6250 }
6251 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006252 return 0;
6253}
6254
Chris Lattner72684fe2005-01-31 05:51:45 +00006255/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6256/// when possible.
6257static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6258 User *CI = cast<User>(SI.getOperand(1));
6259 Value *CastOp = CI->getOperand(0);
6260
6261 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6262 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6263 const Type *SrcPTy = SrcTy->getElementType();
6264
6265 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6266 // If the source is an array, the code below will not succeed. Check to
6267 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6268 // constants.
6269 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6270 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6271 if (ASrcTy->getNumElements() != 0) {
6272 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6273 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6274 SrcTy = cast<PointerType>(CastOp->getType());
6275 SrcPTy = SrcTy->getElementType();
6276 }
6277
6278 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006279 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006280 IC.getTargetData().getTypeSize(DestPTy)) {
6281
6282 // Okay, we are casting from one integer or pointer type to another of
6283 // the same size. Instead of casting the pointer before the store, cast
6284 // the value to be stored.
6285 Value *NewCast;
6286 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6287 NewCast = ConstantExpr::getCast(C, SrcPTy);
6288 else
6289 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6290 SrcPTy,
6291 SI.getOperand(0)->getName()+".c"), SI);
6292
6293 return new StoreInst(NewCast, CastOp);
6294 }
6295 }
6296 }
6297 return 0;
6298}
6299
Chris Lattner31f486c2005-01-31 05:36:43 +00006300Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6301 Value *Val = SI.getOperand(0);
6302 Value *Ptr = SI.getOperand(1);
6303
6304 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006305 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006306 ++NumCombined;
6307 return 0;
6308 }
6309
Chris Lattner5997cf92006-02-08 03:25:32 +00006310 // Do really simple DSE, to catch cases where there are several consequtive
6311 // stores to the same location, separated by a few arithmetic operations. This
6312 // situation often occurs with bitfield accesses.
6313 BasicBlock::iterator BBI = &SI;
6314 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6315 --ScanInsts) {
6316 --BBI;
6317
6318 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6319 // Prev store isn't volatile, and stores to the same location?
6320 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6321 ++NumDeadStore;
6322 ++BBI;
6323 EraseInstFromFunction(*PrevSI);
6324 continue;
6325 }
6326 break;
6327 }
6328
6329 // Don't skip over loads or things that can modify memory.
6330 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6331 break;
6332 }
6333
6334
6335 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00006336
6337 // store X, null -> turns into 'unreachable' in SimplifyCFG
6338 if (isa<ConstantPointerNull>(Ptr)) {
6339 if (!isa<UndefValue>(Val)) {
6340 SI.setOperand(0, UndefValue::get(Val->getType()));
6341 if (Instruction *U = dyn_cast<Instruction>(Val))
6342 WorkList.push_back(U); // Dropped a use.
6343 ++NumCombined;
6344 }
6345 return 0; // Do not modify these!
6346 }
6347
6348 // store undef, Ptr -> noop
6349 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00006350 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006351 ++NumCombined;
6352 return 0;
6353 }
6354
Chris Lattner72684fe2005-01-31 05:51:45 +00006355 // If the pointer destination is a cast, see if we can fold the cast into the
6356 // source instead.
6357 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6358 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6359 return Res;
6360 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6361 if (CE->getOpcode() == Instruction::Cast)
6362 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6363 return Res;
6364
Chris Lattner219175c2005-09-12 23:23:25 +00006365
6366 // If this store is the last instruction in the basic block, and if the block
6367 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00006368 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00006369 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6370 if (BI->isUnconditional()) {
6371 // Check to see if the successor block has exactly two incoming edges. If
6372 // so, see if the other predecessor contains a store to the same location.
6373 // if so, insert a PHI node (if needed) and move the stores down.
6374 BasicBlock *Dest = BI->getSuccessor(0);
6375
6376 pred_iterator PI = pred_begin(Dest);
6377 BasicBlock *Other = 0;
6378 if (*PI != BI->getParent())
6379 Other = *PI;
6380 ++PI;
6381 if (PI != pred_end(Dest)) {
6382 if (*PI != BI->getParent())
6383 if (Other)
6384 Other = 0;
6385 else
6386 Other = *PI;
6387 if (++PI != pred_end(Dest))
6388 Other = 0;
6389 }
6390 if (Other) { // If only one other pred...
6391 BBI = Other->getTerminator();
6392 // Make sure this other block ends in an unconditional branch and that
6393 // there is an instruction before the branch.
6394 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6395 BBI != Other->begin()) {
6396 --BBI;
6397 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6398
6399 // If this instruction is a store to the same location.
6400 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6401 // Okay, we know we can perform this transformation. Insert a PHI
6402 // node now if we need it.
6403 Value *MergedVal = OtherStore->getOperand(0);
6404 if (MergedVal != SI.getOperand(0)) {
6405 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6406 PN->reserveOperandSpace(2);
6407 PN->addIncoming(SI.getOperand(0), SI.getParent());
6408 PN->addIncoming(OtherStore->getOperand(0), Other);
6409 MergedVal = InsertNewInstBefore(PN, Dest->front());
6410 }
6411
6412 // Advance to a place where it is safe to insert the new store and
6413 // insert it.
6414 BBI = Dest->begin();
6415 while (isa<PHINode>(BBI)) ++BBI;
6416 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6417 OtherStore->isVolatile()), *BBI);
6418
6419 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00006420 EraseInstFromFunction(SI);
6421 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00006422 ++NumCombined;
6423 return 0;
6424 }
6425 }
6426 }
6427 }
6428
Chris Lattner31f486c2005-01-31 05:36:43 +00006429 return 0;
6430}
6431
6432
Chris Lattner9eef8a72003-06-04 04:46:00 +00006433Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6434 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00006435 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00006436 BasicBlock *TrueDest;
6437 BasicBlock *FalseDest;
6438 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6439 !isa<Constant>(X)) {
6440 // Swap Destinations and condition...
6441 BI.setCondition(X);
6442 BI.setSuccessor(0, FalseDest);
6443 BI.setSuccessor(1, TrueDest);
6444 return &BI;
6445 }
6446
6447 // Cannonicalize setne -> seteq
6448 Instruction::BinaryOps Op; Value *Y;
6449 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6450 TrueDest, FalseDest)))
6451 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6452 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6453 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6454 std::string Name = I->getName(); I->setName("");
6455 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6456 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00006457 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00006458 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00006459 BI.setSuccessor(0, FalseDest);
6460 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00006461 removeFromWorkList(I);
6462 I->getParent()->getInstList().erase(I);
6463 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00006464 return &BI;
6465 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006466
Chris Lattner9eef8a72003-06-04 04:46:00 +00006467 return 0;
6468}
Chris Lattner1085bdf2002-11-04 16:18:53 +00006469
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006470Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6471 Value *Cond = SI.getCondition();
6472 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6473 if (I->getOpcode() == Instruction::Add)
6474 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6475 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6476 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00006477 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00006478 AddRHS));
6479 SI.setOperand(0, I->getOperand(0));
6480 WorkList.push_back(I);
6481 return &SI;
6482 }
6483 }
6484 return 0;
6485}
6486
Robert Bocchinoa8352962006-01-13 22:48:06 +00006487Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6488 if (ConstantAggregateZero *C =
6489 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6490 // If packed val is constant 0, replace extract with scalar 0
6491 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6492 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6493 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6494 }
6495 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6496 // If packed val is constant with uniform operands, replace EI
6497 // with that operand
6498 Constant *op0 = cast<Constant>(C->getOperand(0));
6499 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6500 if (C->getOperand(i) != op0) return 0;
6501 return ReplaceInstUsesWith(EI, op0);
6502 }
6503 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6504 if (I->hasOneUse()) {
6505 // Push extractelement into predecessor operation if legal and
6506 // profitable to do so
6507 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6508 if (!isa<Constant>(BO->getOperand(0)) &&
6509 !isa<Constant>(BO->getOperand(1)))
6510 return 0;
6511 ExtractElementInst *newEI0 =
6512 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6513 EI.getName());
6514 ExtractElementInst *newEI1 =
6515 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6516 EI.getName());
6517 InsertNewInstBefore(newEI0, EI);
6518 InsertNewInstBefore(newEI1, EI);
6519 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6520 }
6521 switch(I->getOpcode()) {
6522 case Instruction::Load: {
6523 Value *Ptr = InsertCastBefore(I->getOperand(0),
6524 PointerType::get(EI.getType()), EI);
6525 GetElementPtrInst *GEP =
6526 new GetElementPtrInst(Ptr, EI.getOperand(1),
6527 I->getName() + ".gep");
6528 InsertNewInstBefore(GEP, EI);
6529 return new LoadInst(GEP);
6530 }
6531 default:
6532 return 0;
6533 }
6534 }
6535 return 0;
6536}
6537
6538
Chris Lattner99f48c62002-09-02 04:59:56 +00006539void InstCombiner::removeFromWorkList(Instruction *I) {
6540 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6541 WorkList.end());
6542}
6543
Chris Lattner39c98bb2004-12-08 23:43:58 +00006544
6545/// TryToSinkInstruction - Try to move the specified instruction from its
6546/// current block into the beginning of DestBlock, which can only happen if it's
6547/// safe to move the instruction past all of the instructions between it and the
6548/// end of its block.
6549static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6550 assert(I->hasOneUse() && "Invariants didn't hold!");
6551
Chris Lattnerc4f67e62005-10-27 17:13:11 +00006552 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6553 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006554
Chris Lattner39c98bb2004-12-08 23:43:58 +00006555 // Do not sink alloca instructions out of the entry block.
6556 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6557 return false;
6558
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006559 // We can only sink load instructions if there is nothing between the load and
6560 // the end of block that could change the value.
6561 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006562 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6563 Scan != E; ++Scan)
6564 if (Scan->mayWriteToMemory())
6565 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00006566 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00006567
6568 BasicBlock::iterator InsertPos = DestBlock->begin();
6569 while (isa<PHINode>(InsertPos)) ++InsertPos;
6570
Chris Lattner9f269e42005-08-08 19:11:57 +00006571 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00006572 ++NumSunkInst;
6573 return true;
6574}
6575
Chris Lattner113f4f42002-06-25 16:13:24 +00006576bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00006577 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00006578 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00006579
Chris Lattner4ed40f72005-07-07 20:40:38 +00006580 {
6581 // Populate the worklist with the reachable instructions.
6582 std::set<BasicBlock*> Visited;
6583 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6584 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6585 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6586 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00006587
Chris Lattner4ed40f72005-07-07 20:40:38 +00006588 // Do a quick scan over the function. If we find any blocks that are
6589 // unreachable, remove any instructions inside of them. This prevents
6590 // the instcombine code from having to deal with some bad special cases.
6591 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6592 if (!Visited.count(BB)) {
6593 Instruction *Term = BB->getTerminator();
6594 while (Term != BB->begin()) { // Remove instrs bottom-up
6595 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00006596
Chris Lattner4ed40f72005-07-07 20:40:38 +00006597 DEBUG(std::cerr << "IC: DCE: " << *I);
6598 ++NumDeadInst;
6599
6600 if (!I->use_empty())
6601 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6602 I->eraseFromParent();
6603 }
6604 }
6605 }
Chris Lattnerca081252001-12-14 16:52:21 +00006606
6607 while (!WorkList.empty()) {
6608 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6609 WorkList.pop_back();
6610
Misha Brukman632df282002-10-29 23:06:16 +00006611 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00006612 // Check to see if we can DIE the instruction...
6613 if (isInstructionTriviallyDead(I)) {
6614 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006615 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00006616 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00006617 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006618
Chris Lattnercd517ff2005-01-28 19:32:01 +00006619 DEBUG(std::cerr << "IC: DCE: " << *I);
6620
6621 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006622 removeFromWorkList(I);
6623 continue;
6624 }
Chris Lattner99f48c62002-09-02 04:59:56 +00006625
Misha Brukman632df282002-10-29 23:06:16 +00006626 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00006627 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006628 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00006629 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006630 cast<Constant>(Ptr)->isNullValue() &&
6631 !isa<ConstantPointerNull>(C) &&
6632 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00006633 // If this is a constant expr gep that is effectively computing an
6634 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6635 bool isFoldableGEP = true;
6636 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6637 if (!isa<ConstantInt>(I->getOperand(i)))
6638 isFoldableGEP = false;
6639 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00006640 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00006641 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6642 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00006643 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00006644 C = ConstantExpr::getCast(C, I->getType());
6645 }
6646 }
6647
Chris Lattnercd517ff2005-01-28 19:32:01 +00006648 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6649
Chris Lattner99f48c62002-09-02 04:59:56 +00006650 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00006651 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00006652 ReplaceInstUsesWith(*I, C);
6653
Chris Lattner99f48c62002-09-02 04:59:56 +00006654 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006655 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00006656 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006657 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00006658 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006659
Chris Lattner39c98bb2004-12-08 23:43:58 +00006660 // See if we can trivially sink this instruction to a successor basic block.
6661 if (I->hasOneUse()) {
6662 BasicBlock *BB = I->getParent();
6663 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6664 if (UserParent != BB) {
6665 bool UserIsSuccessor = false;
6666 // See if the user is one of our successors.
6667 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6668 if (*SI == UserParent) {
6669 UserIsSuccessor = true;
6670 break;
6671 }
6672
6673 // If the user is one of our immediate successors, and if that successor
6674 // only has us as a predecessors (we'd have to split the critical edge
6675 // otherwise), we can keep going.
6676 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6677 next(pred_begin(UserParent)) == pred_end(UserParent))
6678 // Okay, the CFG is simple enough, try to sink this instruction.
6679 Changed |= TryToSinkInstruction(I, UserParent);
6680 }
6681 }
6682
Chris Lattnerca081252001-12-14 16:52:21 +00006683 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006684 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00006685 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00006686 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00006687 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006688 DEBUG(std::cerr << "IC: Old = " << *I
6689 << " New = " << *Result);
6690
Chris Lattner396dbfe2004-06-09 05:08:07 +00006691 // Everything uses the new instruction now.
6692 I->replaceAllUsesWith(Result);
6693
6694 // Push the new instruction and any users onto the worklist.
6695 WorkList.push_back(Result);
6696 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006697
6698 // Move the name to the new instruction first...
6699 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00006700 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006701
6702 // Insert the new instruction into the basic block...
6703 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00006704 BasicBlock::iterator InsertPos = I;
6705
6706 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6707 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6708 ++InsertPos;
6709
6710 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006711
Chris Lattner63d75af2004-05-01 23:27:23 +00006712 // Make sure that we reprocess all operands now that we reduced their
6713 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00006714 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6715 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6716 WorkList.push_back(OpI);
6717
Chris Lattner396dbfe2004-06-09 05:08:07 +00006718 // Instructions can end up on the worklist more than once. Make sure
6719 // we do not process an instruction that has been deleted.
6720 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00006721
6722 // Erase the old instruction.
6723 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00006724 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00006725 DEBUG(std::cerr << "IC: MOD = " << *I);
6726
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006727 // If the instruction was modified, it's possible that it is now dead.
6728 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00006729 if (isInstructionTriviallyDead(I)) {
6730 // Make sure we process all operands now that we are reducing their
6731 // use counts.
6732 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6733 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6734 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006735
Chris Lattner63d75af2004-05-01 23:27:23 +00006736 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00006737 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00006738 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00006739 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00006740 } else {
6741 WorkList.push_back(Result);
6742 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006743 }
Chris Lattner053c0932002-05-14 15:24:07 +00006744 }
Chris Lattner260ab202002-04-18 17:39:14 +00006745 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00006746 }
6747 }
6748
Chris Lattner260ab202002-04-18 17:39:14 +00006749 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00006750}
6751
Brian Gaeke38b79e82004-07-27 17:43:21 +00006752FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00006753 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00006754}
Brian Gaeke960707c2003-11-11 22:41:34 +00006755