blob: 1fc4211ea74a885a20d284e9e857e68a47d5dafd [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 Lattner4a4c7fe2006-06-28 22:08:15 +000051#include "llvm/Support/Visibility.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 Lattner4a4c7fe2006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000072
Chris Lattner51ea1272004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner2590e512006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner51ea1272004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
91
Chris Lattner99f48c62002-09-02 04:59:56 +000092 // removeFromWorkList - remove all instances of I from the worklist.
93 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000094 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000095 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000096
Chris Lattnerf12cc842002-04-28 21:27:06 +000097 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000098 AU.addRequired<TargetData>();
Owen Andersona6968f82006-07-10 19:03:49 +000099 AU.addPreservedID(LCSSAID);
Chris Lattner820d9712002-10-21 20:00:28 +0000100 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +0000101 }
102
Chris Lattner69193f92004-04-05 01:30:19 +0000103 TargetData &getTargetData() const { return *TD; }
104
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // Visitation implementation - Implement instruction combining for different
106 // instruction types. The semantics are as follows:
107 // Return Value:
108 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000109 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000110 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000111 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000112 Instruction *visitAdd(BinaryOperator &I);
113 Instruction *visitSub(BinaryOperator &I);
114 Instruction *visitMul(BinaryOperator &I);
115 Instruction *visitDiv(BinaryOperator &I);
116 Instruction *visitRem(BinaryOperator &I);
117 Instruction *visitAnd(BinaryOperator &I);
118 Instruction *visitOr (BinaryOperator &I);
119 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000120 Instruction *visitSetCondInst(SetCondInst &I);
121 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
122
Chris Lattner0798af32005-01-13 20:14:25 +0000123 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
124 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000125 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner14553932006-01-06 07:12:35 +0000126 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
127 ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000129 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
130 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000131 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 Instruction *visitCallInst(CallInst &CI);
133 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000134 Instruction *visitPHINode(PHINode &PN);
135 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000136 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000137 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000138 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000139 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000140 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000141 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner39fac442006-04-15 01:39:45 +0000142 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchinoa8352962006-01-13 22:48:06 +0000143 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +0000144 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattner260ab202002-04-18 17:39:14 +0000145
146 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000147 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148
Chris Lattner970c33a2003-06-19 17:00:31 +0000149 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000150 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000151 bool transformConstExprCastCall(CallSite CS);
152
Chris Lattner69193f92004-04-05 01:30:19 +0000153 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 // InsertNewInstBefore - insert an instruction New before instruction Old
155 // in the program. Add the new instruction to the worklist.
156 //
Chris Lattner623826c2004-09-28 21:48:02 +0000157 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000158 assert(New && New->getParent() == 0 &&
159 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 BasicBlock *BB = Old.getParent();
161 BB->getInstList().insert(&Old, New); // Insert inst
162 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000163 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000164 }
165
Chris Lattner7e794272004-09-24 15:21:34 +0000166 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
167 /// This also adds the cast to the worklist. Finally, this returns the
168 /// cast.
169 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
170 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000171
Chris Lattnere79d2492006-04-06 19:19:17 +0000172 if (Constant *CV = dyn_cast<Constant>(V))
173 return ConstantExpr::getCast(CV, Ty);
174
Chris Lattner7e794272004-09-24 15:21:34 +0000175 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
176 WorkList.push_back(C);
177 return C;
178 }
179
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000180 // ReplaceInstUsesWith - This method is to be used when an instruction is
181 // found to be dead, replacable with another preexisting expression. Here
182 // we add all uses of I to the worklist, replace all uses of I with the new
183 // value, then return I, so that the inst combiner will know that I was
184 // modified.
185 //
186 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000187 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000188 if (&I != V) {
189 I.replaceAllUsesWith(V);
190 return &I;
191 } else {
192 // If we are replacing the instruction with itself, this must be in a
193 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000194 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000195 return &I;
196 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000197 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000198
Chris Lattner2590e512006-02-07 06:56:34 +0000199 // UpdateValueUsesWith - This method is to be used when an value is
200 // found to be replacable with another preexisting expression or was
201 // updated. Here we add all uses of I to the worklist, replace all uses of
202 // I with the new value (unless the instruction was just updated), then
203 // return true, so that the inst combiner will know that I was modified.
204 //
205 bool UpdateValueUsesWith(Value *Old, Value *New) {
206 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
207 if (Old != New)
208 Old->replaceAllUsesWith(New);
209 if (Instruction *I = dyn_cast<Instruction>(Old))
210 WorkList.push_back(I);
Chris Lattner5b2edb12006-02-12 08:02:11 +0000211 if (Instruction *I = dyn_cast<Instruction>(New))
212 WorkList.push_back(I);
Chris Lattner2590e512006-02-07 06:56:34 +0000213 return true;
214 }
215
Chris Lattner51ea1272004-02-28 05:22:00 +0000216 // EraseInstFromFunction - When dealing with an instruction that has side
217 // effects or produces a void value, we can't rely on DCE to delete the
218 // instruction. Instead, visit methods should return the value returned by
219 // this function.
220 Instruction *EraseInstFromFunction(Instruction &I) {
221 assert(I.use_empty() && "Cannot erase instruction that is used!");
222 AddUsesToWorkList(I);
223 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000224 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000225 return 0; // Don't do anything with FI
226 }
227
Chris Lattner3ac7c262003-08-13 20:16:26 +0000228 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000229 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
230 /// InsertBefore instruction. This is specialized a bit to avoid inserting
231 /// casts that are known to not do anything...
232 ///
233 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
234 Instruction *InsertBefore);
235
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000237 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000239
Chris Lattner0157e7f2006-02-11 09:31:47 +0000240 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
241 uint64_t &KnownZero, uint64_t &KnownOne,
242 unsigned Depth = 0);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000243
244 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
245 // PHI node as operand #0, see if we can fold the instruction into the PHI
246 // (which is only possible if all operands to the PHI are constants).
247 Instruction *FoldOpIntoPhi(Instruction &I);
248
Chris Lattner7515cab2004-11-14 19:13:23 +0000249 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
250 // operator and they all are only used by the PHI, PHI together their
251 // inputs, and do the operation once, to the result of the PHI.
252 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
253
Chris Lattnerba1cb382003-09-19 17:17:26 +0000254 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
255 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattneraf517572005-09-18 04:24:45 +0000256
257 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
258 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000259 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
260 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000261 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerc482a9e2006-06-15 19:07:26 +0000262 Instruction *MatchBSwap(BinaryOperator &I);
263
Chris Lattner1ebbe6a2006-05-13 02:06:03 +0000264 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattner260ab202002-04-18 17:39:14 +0000265 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000266
Chris Lattnerc8b70922002-07-26 21:12:46 +0000267 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000268}
269
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000271// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272static unsigned getComplexity(Value *V) {
273 if (isa<Instruction>(V)) {
274 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000275 return 3;
276 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000277 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000278 if (isa<Argument>(V)) return 3;
279 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000280}
Chris Lattner260ab202002-04-18 17:39:14 +0000281
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282// isOnlyUse - Return true if this instruction will be deleted if we stop using
283// it.
284static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000285 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000286}
287
Chris Lattnere79e8542004-02-23 06:38:22 +0000288// getPromotedType - Return the specified type promoted as it would be to pass
289// though a va_arg area...
290static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000291 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000292 case Type::SByteTyID:
293 case Type::ShortTyID: return Type::IntTy;
294 case Type::UByteTyID:
295 case Type::UShortTyID: return Type::UIntTy;
296 case Type::FloatTyID: return Type::DoubleTy;
297 default: return Ty;
298 }
299}
300
Chris Lattner567b81f2005-09-13 00:40:14 +0000301/// isCast - If the specified operand is a CastInst or a constant expr cast,
302/// return the operand value, otherwise return null.
303static Value *isCast(Value *V) {
304 if (CastInst *I = dyn_cast<CastInst>(V))
305 return I->getOperand(0);
306 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
307 if (CE->getOpcode() == Instruction::Cast)
308 return CE->getOperand(0);
309 return 0;
310}
311
Chris Lattner1d441ad2006-05-06 09:00:16 +0000312enum CastType {
313 Noop = 0,
314 Truncate = 1,
315 Signext = 2,
316 Zeroext = 3
317};
318
319/// getCastType - In the future, we will split the cast instruction into these
320/// various types. Until then, we have to do the analysis here.
321static CastType getCastType(const Type *Src, const Type *Dest) {
322 assert(Src->isIntegral() && Dest->isIntegral() &&
323 "Only works on integral types!");
324 unsigned SrcSize = Src->getPrimitiveSizeInBits();
325 unsigned DestSize = Dest->getPrimitiveSizeInBits();
326
327 if (SrcSize == DestSize) return Noop;
328 if (SrcSize > DestSize) return Truncate;
329 if (Src->isSigned()) return Signext;
330 return Zeroext;
331}
332
333
334// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
335// instruction.
336//
337static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
338 const Type *DstTy, TargetData *TD) {
339
340 // It is legal to eliminate the instruction if casting A->B->A if the sizes
341 // are identical and the bits don't get reinterpreted (for example
342 // int->float->int would not be allowed).
343 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
344 return true;
345
346 // If we are casting between pointer and integer types, treat pointers as
347 // integers of the appropriate size for the code below.
348 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
349 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
350 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
351
352 // Allow free casting and conversion of sizes as long as the sign doesn't
353 // change...
354 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
355 CastType FirstCast = getCastType(SrcTy, MidTy);
356 CastType SecondCast = getCastType(MidTy, DstTy);
357
358 // Capture the effect of these two casts. If the result is a legal cast,
359 // the CastType is stored here, otherwise a special code is used.
360 static const unsigned CastResult[] = {
361 // First cast is noop
362 0, 1, 2, 3,
363 // First cast is a truncate
364 1, 1, 4, 4, // trunc->extend is not safe to eliminate
365 // First cast is a sign ext
366 2, 5, 2, 4, // signext->zeroext never ok
367 // First cast is a zero ext
368 3, 5, 3, 3,
369 };
370
371 unsigned Result = CastResult[FirstCast*4+SecondCast];
372 switch (Result) {
373 default: assert(0 && "Illegal table value!");
374 case 0:
375 case 1:
376 case 2:
377 case 3:
378 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
379 // truncates, we could eliminate more casts.
380 return (unsigned)getCastType(SrcTy, DstTy) == Result;
381 case 4:
382 return false; // Not possible to eliminate this here.
383 case 5:
384 // Sign or zero extend followed by truncate is always ok if the result
385 // is a truncate or noop.
386 CastType ResultCast = getCastType(SrcTy, DstTy);
387 if (ResultCast == Noop || ResultCast == Truncate)
388 return true;
389 // Otherwise we are still growing the value, we are only safe if the
390 // result will match the sign/zeroextendness of the result.
391 return ResultCast == FirstCast;
392 }
393 }
394
395 // If this is a cast from 'float -> double -> integer', cast from
396 // 'float -> integer' directly, as the value isn't changed by the
397 // float->double conversion.
398 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
399 DstTy->isIntegral() &&
400 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
401 return true;
402
403 // Packed type conversions don't modify bits.
404 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
405 return true;
406
407 return false;
408}
409
410/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
411/// in any code being generated. It does not require codegen if V is simple
412/// enough or if the cast can be folded into other casts.
413static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
414 if (V->getType() == Ty || isa<Constant>(V)) return false;
415
416 // If this is a noop cast, it isn't real codegen.
417 if (V->getType()->isLosslesslyConvertibleTo(Ty))
418 return false;
419
Chris Lattner99155be2006-05-25 23:24:33 +0000420 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner1d441ad2006-05-06 09:00:16 +0000421 if (const CastInst *CI = dyn_cast<CastInst>(V))
422 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
423 TD))
424 return false;
425 return true;
426}
427
428/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
429/// InsertBefore instruction. This is specialized a bit to avoid inserting
430/// casts that are known to not do anything...
431///
432Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
433 Instruction *InsertBefore) {
434 if (V->getType() == DestTy) return V;
435 if (Constant *C = dyn_cast<Constant>(V))
436 return ConstantExpr::getCast(C, DestTy);
437
438 CastInst *CI = new CastInst(V, DestTy, V->getName());
439 InsertNewInstBefore(CI, *InsertBefore);
440 return CI;
441}
442
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000443// SimplifyCommutative - This performs a few simplifications for commutative
444// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000445//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000446// 1. Order operands such that they are listed from right (least complex) to
447// left (most complex). This puts constants before unary operators before
448// binary operators.
449//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000450// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
451// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000452//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000453bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000454 bool Changed = false;
455 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
456 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000457
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000458 if (!I.isAssociative()) return Changed;
459 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000460 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
461 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
462 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000463 Constant *Folded = ConstantExpr::get(I.getOpcode(),
464 cast<Constant>(I.getOperand(1)),
465 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000466 I.setOperand(0, Op->getOperand(0));
467 I.setOperand(1, Folded);
468 return true;
469 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
470 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
471 isOnlyUse(Op) && isOnlyUse(Op1)) {
472 Constant *C1 = cast<Constant>(Op->getOperand(1));
473 Constant *C2 = cast<Constant>(Op1->getOperand(1));
474
475 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000476 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000477 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
478 Op1->getOperand(0),
479 Op1->getName(), &I);
480 WorkList.push_back(New);
481 I.setOperand(0, New);
482 I.setOperand(1, Folded);
483 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000484 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000485 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000486 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000487}
Chris Lattnerca081252001-12-14 16:52:21 +0000488
Chris Lattnerbb74e222003-03-10 23:06:50 +0000489// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
490// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000491//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000492static inline Value *dyn_castNegVal(Value *V) {
493 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000494 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495
Chris Lattner9ad0d552004-12-14 20:08:06 +0000496 // Constants can be considered to be negated values if they can be folded.
497 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
498 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000499 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000500}
501
Chris Lattnerbb74e222003-03-10 23:06:50 +0000502static inline Value *dyn_castNotVal(Value *V) {
503 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000504 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000505
506 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000507 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000508 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000509 return 0;
510}
511
Chris Lattner7fb29e12003-03-11 00:12:48 +0000512// dyn_castFoldableMul - If this value is a multiply that can be folded into
513// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000514// non-constant operand of the multiply, and set CST to point to the multiplier.
515// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000516//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000517static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000518 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000519 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000520 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000522 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000523 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000524 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000525 // The multiplier is really 1 << CST.
526 Constant *One = ConstantInt::get(V->getType(), 1);
527 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
528 return I->getOperand(0);
529 }
530 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000531 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000532}
Chris Lattner31ae8632002-08-14 17:51:49 +0000533
Chris Lattner0798af32005-01-13 20:14:25 +0000534/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
535/// expression, return it.
536static User *dyn_castGetElementPtr(Value *V) {
537 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
539 if (CE->getOpcode() == Instruction::GetElementPtr)
540 return cast<User>(V);
541 return false;
542}
543
Chris Lattner623826c2004-09-28 21:48:02 +0000544// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000545static ConstantInt *AddOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getAdd(C,
547 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000548}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000549static ConstantInt *SubOne(ConstantInt *C) {
550 return cast<ConstantInt>(ConstantExpr::getSub(C,
551 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000552}
553
Chris Lattner0157e7f2006-02-11 09:31:47 +0000554/// GetConstantInType - Return a ConstantInt with the specified type and value.
555///
Chris Lattneree0f2802006-02-12 02:07:56 +0000556static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000557 if (Ty->isUnsigned())
558 return ConstantUInt::get(Ty, Val);
Chris Lattneree0f2802006-02-12 02:07:56 +0000559 else if (Ty->getTypeID() == Type::BoolTyID)
560 return ConstantBool::get(Val);
Chris Lattner0157e7f2006-02-11 09:31:47 +0000561 int64_t SVal = Val;
562 SVal <<= 64-Ty->getPrimitiveSizeInBits();
563 SVal >>= 64-Ty->getPrimitiveSizeInBits();
564 return ConstantSInt::get(Ty, SVal);
565}
566
567
Chris Lattner4534dd592006-02-09 07:38:58 +0000568/// ComputeMaskedBits - Determine which of the bits specified in Mask are
569/// known to be either zero or one and return them in the KnownZero/KnownOne
570/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
571/// processing.
572static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
573 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000574 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
575 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattnerc3ebf402006-02-07 07:27:52 +0000576 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner0b3557f2005-09-24 23:43:33 +0000577 // optimized based on the contradictory assumption that it is non-zero.
578 // Because instcombine aggressively folds operations with undef args anyway,
579 // this won't lose us code quality.
Chris Lattner4534dd592006-02-09 07:38:58 +0000580 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
581 // We know all of the bits for a constant!
Chris Lattner0157e7f2006-02-11 09:31:47 +0000582 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner4534dd592006-02-09 07:38:58 +0000583 KnownZero = ~KnownOne & Mask;
584 return;
585 }
586
587 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner92a68652006-02-07 08:05:22 +0000588 if (Depth == 6 || Mask == 0)
Chris Lattner4534dd592006-02-09 07:38:58 +0000589 return; // Limit search depth.
590
591 uint64_t KnownZero2, KnownOne2;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000592 Instruction *I = dyn_cast<Instruction>(V);
593 if (!I) return;
594
Chris Lattnerfb296922006-05-04 17:33:35 +0000595 Mask &= V->getType()->getIntegralTypeMask();
596
Chris Lattner0157e7f2006-02-11 09:31:47 +0000597 switch (I->getOpcode()) {
598 case Instruction::And:
599 // If either the LHS or the RHS are Zero, the result is zero.
600 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
601 Mask &= ~KnownZero;
602 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
605
606 // Output known-1 bits are only known if set in both the LHS & RHS.
607 KnownOne &= KnownOne2;
608 // Output known-0 are known to be clear if zero in either the LHS | RHS.
609 KnownZero |= KnownZero2;
610 return;
611 case Instruction::Or:
612 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
613 Mask &= ~KnownOne;
614 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
616 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
617
618 // Output known-0 bits are only known if clear in both the LHS & RHS.
619 KnownZero &= KnownZero2;
620 // Output known-1 are known to be set if set in either the LHS | RHS.
621 KnownOne |= KnownOne2;
622 return;
623 case Instruction::Xor: {
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
626 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
627 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
628
629 // Output known-0 bits are known if clear or set in both the LHS & RHS.
630 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
631 // Output known-1 are known to be set if set in only one of the LHS, RHS.
632 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
633 KnownZero = KnownZeroOut;
634 return;
635 }
636 case Instruction::Select:
637 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
641
642 // Only known if known in both the LHS and RHS.
643 KnownOne &= KnownOne2;
644 KnownZero &= KnownZero2;
645 return;
646 case Instruction::Cast: {
647 const Type *SrcTy = I->getOperand(0)->getType();
648 if (!SrcTy->isIntegral()) return;
649
650 // If this is an integer truncate or noop, just look in the input.
651 if (SrcTy->getPrimitiveSizeInBits() >=
652 I->getType()->getPrimitiveSizeInBits()) {
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner4534dd592006-02-09 07:38:58 +0000654 return;
655 }
Chris Lattner4534dd592006-02-09 07:38:58 +0000656
Chris Lattner0157e7f2006-02-11 09:31:47 +0000657 // Sign or Zero extension. Compute the bits in the result that are not
658 // present in the input.
659 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
660 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner62010c42005-10-09 06:36:35 +0000661
Chris Lattner0157e7f2006-02-11 09:31:47 +0000662 // Handle zero extension.
663 if (!SrcTy->isSigned()) {
664 Mask &= SrcTy->getIntegralTypeMask();
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
667 // The top bits are known to be zero.
668 KnownZero |= NewBits;
669 } else {
670 // Sign extension.
671 Mask &= SrcTy->getIntegralTypeMask();
672 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner92a68652006-02-07 08:05:22 +0000674
Chris Lattner0157e7f2006-02-11 09:31:47 +0000675 // If the sign bit of the input is known set or clear, then we know the
676 // top bits of the result.
677 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
678 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner4534dd592006-02-09 07:38:58 +0000679 KnownZero |= NewBits;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000680 KnownOne &= ~NewBits;
681 } else if (KnownOne & InSignBit) { // Input sign bit known set
682 KnownOne |= NewBits;
683 KnownZero &= ~NewBits;
684 } else { // Input sign bit unknown
685 KnownZero &= ~NewBits;
686 KnownOne &= ~NewBits;
687 }
688 }
689 return;
690 }
691 case Instruction::Shl:
692 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
693 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
694 Mask >>= SA->getValue();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 KnownZero <<= SA->getValue();
698 KnownOne <<= SA->getValue();
699 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
700 return;
701 }
702 break;
703 case Instruction::Shr:
704 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
705 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
706 // Compute the new bits that are at the top now.
707 uint64_t HighBits = (1ULL << SA->getValue())-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
709
710 if (I->getType()->isUnsigned()) { // Unsigned shift right.
711 Mask <<= SA->getValue();
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= SA->getValue();
715 KnownOne >>= SA->getValue();
716 KnownZero |= HighBits; // high bits known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +0000717 } else {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000718 Mask <<= SA->getValue();
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
720 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
721 KnownZero >>= SA->getValue();
722 KnownOne >>= SA->getValue();
723
724 // Handle the sign bits.
725 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
726 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
727
728 if (KnownZero & SignBit) { // New bits are known zero.
729 KnownZero |= HighBits;
730 } else if (KnownOne & SignBit) { // New bits are known one.
731 KnownOne |= HighBits;
Chris Lattner4534dd592006-02-09 07:38:58 +0000732 }
733 }
734 return;
Chris Lattner62010c42005-10-09 06:36:35 +0000735 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000736 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000737 }
Chris Lattner92a68652006-02-07 08:05:22 +0000738}
739
740/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
741/// this predicate to simplify operations downstream. Mask is known to be zero
742/// for bits that V cannot have.
743static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner4534dd592006-02-09 07:38:58 +0000744 uint64_t KnownZero, KnownOne;
745 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 return (KnownZero & Mask) == Mask;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000748}
749
Chris Lattner0157e7f2006-02-11 09:31:47 +0000750/// ShrinkDemandedConstant - Check to see if the specified operand of the
751/// specified instruction is a constant integer. If so, check to see if there
752/// are any bits set in the constant that are not demanded. If so, shrink the
753/// constant and return true.
754static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
755 uint64_t Demanded) {
756 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
757 if (!OpC) return false;
758
759 // If there are no bits set that aren't demanded, nothing to do.
760 if ((~Demanded & OpC->getZExtValue()) == 0)
761 return false;
762
763 // This is producing any bits that are not needed, shrink the RHS.
764 uint64_t Val = Demanded & OpC->getZExtValue();
765 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
766 return true;
767}
768
Chris Lattneree0f2802006-02-12 02:07:56 +0000769// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
770// set of known zero and one bits, compute the maximum and minimum values that
771// could have the specified known zero and known one bits, returning them in
772// min/max.
773static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
774 uint64_t KnownZero,
775 uint64_t KnownOne,
776 int64_t &Min, int64_t &Max) {
777 uint64_t TypeBits = Ty->getIntegralTypeMask();
778 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
779
780 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
781
782 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
783 // bit if it is unknown.
784 Min = KnownOne;
785 Max = KnownOne|UnknownBits;
786
787 if (SignBit & UnknownBits) { // Sign bit is unknown
788 Min |= SignBit;
789 Max &= ~SignBit;
790 }
791
792 // Sign extend the min/max values.
793 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
794 Min = (Min << ShAmt) >> ShAmt;
795 Max = (Max << ShAmt) >> ShAmt;
796}
797
798// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
799// a set of known zero and one bits, compute the maximum and minimum values that
800// could have the specified known zero and known one bits, returning them in
801// min/max.
802static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
803 uint64_t KnownZero,
804 uint64_t KnownOne,
805 uint64_t &Min,
806 uint64_t &Max) {
807 uint64_t TypeBits = Ty->getIntegralTypeMask();
808 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
809
810 // The minimum value is when the unknown bits are all zeros.
811 Min = KnownOne;
812 // The maximum value is when the unknown bits are all ones.
813 Max = KnownOne|UnknownBits;
814}
Chris Lattner0157e7f2006-02-11 09:31:47 +0000815
816
817/// SimplifyDemandedBits - Look at V. At this point, we know that only the
818/// DemandedMask bits of the result of V are ever used downstream. If we can
819/// use this information to simplify V, do so and return true. Otherwise,
820/// analyze the expression and return a mask of KnownOne and KnownZero bits for
821/// the expression (used to simplify the caller). The KnownZero/One bits may
822/// only be accurate for those bits in the DemandedMask.
823bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
824 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner2590e512006-02-07 06:56:34 +0000825 unsigned Depth) {
Chris Lattner0157e7f2006-02-11 09:31:47 +0000826 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
827 // We know all of the bits for a constant!
828 KnownOne = CI->getZExtValue() & DemandedMask;
829 KnownZero = ~KnownOne & DemandedMask;
830 return false;
831 }
832
833 KnownZero = KnownOne = 0;
Chris Lattner2590e512006-02-07 06:56:34 +0000834 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner0157e7f2006-02-11 09:31:47 +0000835 if (Depth != 0) { // Not at the root.
836 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
837 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner2590e512006-02-07 06:56:34 +0000838 return false;
Chris Lattner0157e7f2006-02-11 09:31:47 +0000839 }
Chris Lattner2590e512006-02-07 06:56:34 +0000840 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner0157e7f2006-02-11 09:31:47 +0000841 // just set the DemandedMask to all bits.
842 DemandedMask = V->getType()->getIntegralTypeMask();
843 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner92a68652006-02-07 08:05:22 +0000844 if (V != UndefValue::get(V->getType()))
845 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
846 return false;
Chris Lattner2590e512006-02-07 06:56:34 +0000847 } else if (Depth == 6) { // Limit search depth.
848 return false;
849 }
850
851 Instruction *I = dyn_cast<Instruction>(V);
852 if (!I) return false; // Only analyze instructions.
853
Chris Lattnerfb296922006-05-04 17:33:35 +0000854 DemandedMask &= V->getType()->getIntegralTypeMask();
855
Chris Lattner0157e7f2006-02-11 09:31:47 +0000856 uint64_t KnownZero2, KnownOne2;
Chris Lattner2590e512006-02-07 06:56:34 +0000857 switch (I->getOpcode()) {
858 default: break;
859 case Instruction::And:
Chris Lattner0157e7f2006-02-11 09:31:47 +0000860 // If either the LHS or the RHS are Zero, the result is zero.
861 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
862 KnownZero, KnownOne, Depth+1))
863 return true;
864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
865
866 // If something is known zero on the RHS, the bits aren't demanded on the
867 // LHS.
868 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
869 KnownZero2, KnownOne2, Depth+1))
870 return true;
871 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
872
873 // If all of the demanded bits are known one on one side, return the other.
874 // These bits cannot contribute to the result of the 'and'.
875 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
878 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000879
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
882 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
883
Chris Lattner0157e7f2006-02-11 09:31:47 +0000884 // If the RHS is a constant, see if we can simplify it.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000885 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000886 return UpdateValueUsesWith(I, I);
887
888 // Output known-1 bits are only known if set in both the LHS & RHS.
889 KnownOne &= KnownOne2;
890 // Output known-0 are known to be clear if zero in either the LHS | RHS.
891 KnownZero |= KnownZero2;
892 break;
893 case Instruction::Or:
894 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
895 KnownZero, KnownOne, Depth+1))
896 return true;
897 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
898 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
899 KnownZero2, KnownOne2, Depth+1))
900 return true;
901 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
902
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'or'.
Jeff Cohen0add83e2006-02-18 03:20:33 +0000905 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000906 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohen0add83e2006-02-18 03:20:33 +0000907 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner0157e7f2006-02-11 09:31:47 +0000908 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner5b2edb12006-02-12 08:02:11 +0000909
910 // If all of the potentially set bits on one side are known to be set on
911 // the other side, just use the 'other' side.
912 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
913 (DemandedMask & (~KnownZero)))
914 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman8a77efe2006-02-16 21:11:51 +0000915 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
916 (DemandedMask & (~KnownZero2)))
917 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner0157e7f2006-02-11 09:31:47 +0000918
919 // If the RHS is a constant, see if we can simplify it.
920 if (ShrinkDemandedConstant(I, 1, DemandedMask))
921 return UpdateValueUsesWith(I, I);
922
923 // Output known-0 bits are only known if clear in both the LHS & RHS.
924 KnownZero &= KnownZero2;
925 // Output known-1 are known to be set if set in either the LHS | RHS.
926 KnownOne |= KnownOne2;
927 break;
928 case Instruction::Xor: {
929 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
930 KnownZero, KnownOne, Depth+1))
931 return true;
932 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
933 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
934 KnownZero2, KnownOne2, Depth+1))
935 return true;
936 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
937
938 // If all of the demanded bits are known zero on one side, return the other.
939 // These bits cannot contribute to the result of the 'xor'.
940 if ((DemandedMask & KnownZero) == DemandedMask)
941 return UpdateValueUsesWith(I, I->getOperand(0));
942 if ((DemandedMask & KnownZero2) == DemandedMask)
943 return UpdateValueUsesWith(I, I->getOperand(1));
944
945 // Output known-0 bits are known if clear or set in both the LHS & RHS.
946 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
947 // Output known-1 are known to be set if set in only one of the LHS, RHS.
948 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
949
950 // If all of the unknown bits are known to be zero on one side or the other
951 // (but not both) turn this into an *inclusive* or.
Chris Lattner5b2edb12006-02-12 08:02:11 +0000952 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner0157e7f2006-02-11 09:31:47 +0000953 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
954 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
955 Instruction *Or =
956 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
957 I->getName());
958 InsertNewInstBefore(Or, *I);
959 return UpdateValueUsesWith(I, Or);
Chris Lattner2590e512006-02-07 06:56:34 +0000960 }
961 }
Chris Lattner0157e7f2006-02-11 09:31:47 +0000962
Chris Lattner5b2edb12006-02-12 08:02:11 +0000963 // If all of the demanded bits on one side are known, and all of the set
964 // bits on that side are also known to be set on the other side, turn this
965 // into an AND, as we know the bits will be cleared.
966 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
967 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
968 if ((KnownOne & KnownOne2) == KnownOne) {
969 Constant *AndC = GetConstantInType(I->getType(),
970 ~KnownOne & DemandedMask);
971 Instruction *And =
972 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
973 InsertNewInstBefore(And, *I);
974 return UpdateValueUsesWith(I, And);
975 }
976 }
977
Chris Lattner0157e7f2006-02-11 09:31:47 +0000978 // If the RHS is a constant, see if we can simplify it.
979 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
980 if (ShrinkDemandedConstant(I, 1, DemandedMask))
981 return UpdateValueUsesWith(I, I);
982
983 KnownZero = KnownZeroOut;
984 KnownOne = KnownOneOut;
985 break;
986 }
987 case Instruction::Select:
988 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
989 KnownZero, KnownOne, Depth+1))
990 return true;
991 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
992 KnownZero2, KnownOne2, Depth+1))
993 return true;
994 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
995 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
996
997 // If the operands are constants, see if we can simplify them.
998 if (ShrinkDemandedConstant(I, 1, DemandedMask))
999 return UpdateValueUsesWith(I, I);
1000 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1001 return UpdateValueUsesWith(I, I);
1002
1003 // Only known if known in both the LHS and RHS.
1004 KnownOne &= KnownOne2;
1005 KnownZero &= KnownZero2;
1006 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001007 case Instruction::Cast: {
1008 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001009 if (!SrcTy->isIntegral()) return false;
Chris Lattner2590e512006-02-07 06:56:34 +00001010
Chris Lattner0157e7f2006-02-11 09:31:47 +00001011 // If this is an integer truncate or noop, just look in the input.
1012 if (SrcTy->getPrimitiveSizeInBits() >=
1013 I->getType()->getPrimitiveSizeInBits()) {
1014 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1015 KnownZero, KnownOne, Depth+1))
1016 return true;
1017 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1018 break;
1019 }
1020
1021 // Sign or Zero extension. Compute the bits in the result that are not
1022 // present in the input.
1023 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1024 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1025
1026 // Handle zero extension.
1027 if (!SrcTy->isSigned()) {
1028 DemandedMask &= SrcTy->getIntegralTypeMask();
1029 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1030 KnownZero, KnownOne, Depth+1))
1031 return true;
1032 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1033 // The top bits are known to be zero.
1034 KnownZero |= NewBits;
1035 } else {
1036 // Sign extension.
Chris Lattner7d852282006-02-13 22:41:07 +00001037 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1038 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1039
1040 // If any of the sign extended bits are demanded, we know that the sign
1041 // bit is demanded.
1042 if (NewBits & DemandedMask)
1043 InputDemandedBits |= InSignBit;
1044
1045 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001046 KnownZero, KnownOne, Depth+1))
1047 return true;
1048 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1049
1050 // If the sign bit of the input is known set or clear, then we know the
1051 // top bits of the result.
Chris Lattner2590e512006-02-07 06:56:34 +00001052
Chris Lattner0157e7f2006-02-11 09:31:47 +00001053 // If the input sign bit is known zero, or if the NewBits are not demanded
1054 // convert this into a zero extension.
1055 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner2590e512006-02-07 06:56:34 +00001056 // Convert to unsigned first.
Chris Lattner44314822006-02-07 19:07:40 +00001057 Instruction *NewVal;
Chris Lattner2590e512006-02-07 06:56:34 +00001058 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattner44314822006-02-07 19:07:40 +00001059 I->getOperand(0)->getName());
1060 InsertNewInstBefore(NewVal, *I);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001061 // Then cast that to the destination type.
Chris Lattner44314822006-02-07 19:07:40 +00001062 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1063 InsertNewInstBefore(NewVal, *I);
Chris Lattner2590e512006-02-07 06:56:34 +00001064 return UpdateValueUsesWith(I, NewVal);
Chris Lattner0157e7f2006-02-11 09:31:47 +00001065 } else if (KnownOne & InSignBit) { // Input sign bit known set
1066 KnownOne |= NewBits;
1067 KnownZero &= ~NewBits;
1068 } else { // Input sign bit unknown
1069 KnownZero &= ~NewBits;
1070 KnownOne &= ~NewBits;
Chris Lattner2590e512006-02-07 06:56:34 +00001071 }
Chris Lattner2590e512006-02-07 06:56:34 +00001072 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001073 break;
Chris Lattner2590e512006-02-07 06:56:34 +00001074 }
Chris Lattner2590e512006-02-07 06:56:34 +00001075 case Instruction::Shl:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001076 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1077 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1078 KnownZero, KnownOne, Depth+1))
1079 return true;
1080 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1081 KnownZero <<= SA->getValue();
1082 KnownOne <<= SA->getValue();
1083 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1084 }
Chris Lattner2590e512006-02-07 06:56:34 +00001085 break;
1086 case Instruction::Shr:
Chris Lattner0157e7f2006-02-11 09:31:47 +00001087 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1088 unsigned ShAmt = SA->getValue();
1089
1090 // Compute the new bits that are at the top now.
1091 uint64_t HighBits = (1ULL << ShAmt)-1;
1092 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattner68e74752006-02-13 06:09:08 +00001093 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner0157e7f2006-02-11 09:31:47 +00001094 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001095 if (SimplifyDemandedBits(I->getOperand(0),
1096 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001097 KnownZero, KnownOne, Depth+1))
1098 return true;
1099 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001100 KnownZero &= TypeMask;
1101 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001102 KnownZero >>= ShAmt;
1103 KnownOne >>= ShAmt;
1104 KnownZero |= HighBits; // high bits known zero.
1105 } else { // Signed shift right.
Chris Lattner68e74752006-02-13 06:09:08 +00001106 if (SimplifyDemandedBits(I->getOperand(0),
1107 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner0157e7f2006-02-11 09:31:47 +00001108 KnownZero, KnownOne, Depth+1))
1109 return true;
1110 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner68e74752006-02-13 06:09:08 +00001111 KnownZero &= TypeMask;
1112 KnownOne &= TypeMask;
Chris Lattner0157e7f2006-02-11 09:31:47 +00001113 KnownZero >>= SA->getValue();
1114 KnownOne >>= SA->getValue();
1115
1116 // Handle the sign bits.
1117 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1118 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1119
1120 // If the input sign bit is known to be zero, or if none of the top bits
1121 // are demanded, turn this into an unsigned shift right.
1122 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1123 // Convert the input to unsigned.
1124 Instruction *NewVal;
1125 NewVal = new CastInst(I->getOperand(0),
1126 I->getType()->getUnsignedVersion(),
1127 I->getOperand(0)->getName());
1128 InsertNewInstBefore(NewVal, *I);
1129 // Perform the unsigned shift right.
1130 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1131 InsertNewInstBefore(NewVal, *I);
1132 // Then cast that to the destination type.
1133 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1134 InsertNewInstBefore(NewVal, *I);
1135 return UpdateValueUsesWith(I, NewVal);
1136 } else if (KnownOne & SignBit) { // New bits are known one.
1137 KnownOne |= HighBits;
1138 }
Chris Lattner2590e512006-02-07 06:56:34 +00001139 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001140 }
Chris Lattner2590e512006-02-07 06:56:34 +00001141 break;
1142 }
Chris Lattner0157e7f2006-02-11 09:31:47 +00001143
1144 // If the client is only demanding bits that we know, return the known
1145 // constant.
1146 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1147 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner2590e512006-02-07 06:56:34 +00001148 return false;
1149}
1150
Chris Lattner623826c2004-09-28 21:48:02 +00001151// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1152// true when both operands are equal...
1153//
1154static bool isTrueWhenEqual(Instruction &I) {
1155 return I.getOpcode() == Instruction::SetEQ ||
1156 I.getOpcode() == Instruction::SetGE ||
1157 I.getOpcode() == Instruction::SetLE;
1158}
Chris Lattnerb8b97502003-08-13 19:01:45 +00001159
1160/// AssociativeOpt - Perform an optimization on an associative operator. This
1161/// function is designed to check a chain of associative operators for a
1162/// potential to apply a certain optimization. Since the optimization may be
1163/// applicable if the expression was reassociated, this checks the chain, then
1164/// reassociates the expression as necessary to expose the optimization
1165/// opportunity. This makes use of a special Functor, which must define
1166/// 'shouldApply' and 'apply' methods.
1167///
1168template<typename Functor>
1169Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1170 unsigned Opcode = Root.getOpcode();
1171 Value *LHS = Root.getOperand(0);
1172
1173 // Quick check, see if the immediate LHS matches...
1174 if (F.shouldApply(LHS))
1175 return F.apply(Root);
1176
1177 // Otherwise, if the LHS is not of the same opcode as the root, return.
1178 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001179 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001180 // Should we apply this transform to the RHS?
1181 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1182
1183 // If not to the RHS, check to see if we should apply to the LHS...
1184 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1185 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1186 ShouldApply = true;
1187 }
1188
1189 // If the functor wants to apply the optimization to the RHS of LHSI,
1190 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1191 if (ShouldApply) {
1192 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001193
Chris Lattnerb8b97502003-08-13 19:01:45 +00001194 // Now all of the instructions are in the current basic block, go ahead
1195 // and perform the reassociation.
1196 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1197
1198 // First move the selected RHS to the LHS of the root...
1199 Root.setOperand(0, LHSI->getOperand(1));
1200
1201 // Make what used to be the LHS of the root be the user of the root...
1202 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +00001203 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +00001204 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1205 return 0;
1206 }
Chris Lattner284d3b02004-04-16 18:08:07 +00001207 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +00001208 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +00001209 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1210 BasicBlock::iterator ARI = &Root; ++ARI;
1211 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1212 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +00001213
1214 // Now propagate the ExtraOperand down the chain of instructions until we
1215 // get to LHSI.
1216 while (TmpLHSI != LHSI) {
1217 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +00001218 // Move the instruction to immediately before the chain we are
1219 // constructing to avoid breaking dominance properties.
1220 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1221 BB->getInstList().insert(ARI, NextLHSI);
1222 ARI = NextLHSI;
1223
Chris Lattnerb8b97502003-08-13 19:01:45 +00001224 Value *NextOp = NextLHSI->getOperand(1);
1225 NextLHSI->setOperand(1, ExtraOperand);
1226 TmpLHSI = NextLHSI;
1227 ExtraOperand = NextOp;
1228 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001229
Chris Lattnerb8b97502003-08-13 19:01:45 +00001230 // Now that the instructions are reassociated, have the functor perform
1231 // the transformation...
1232 return F.apply(Root);
1233 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001234
Chris Lattnerb8b97502003-08-13 19:01:45 +00001235 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1236 }
1237 return 0;
1238}
1239
1240
1241// AddRHS - Implements: X + X --> X << 1
1242struct AddRHS {
1243 Value *RHS;
1244 AddRHS(Value *rhs) : RHS(rhs) {}
1245 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1246 Instruction *apply(BinaryOperator &Add) const {
1247 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1248 ConstantInt::get(Type::UByteTy, 1));
1249 }
1250};
1251
1252// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1253// iff C1&C2 == 0
1254struct AddMaskingAnd {
1255 Constant *C2;
1256 AddMaskingAnd(Constant *c) : C2(c) {}
1257 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +00001258 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001259 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +00001260 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +00001261 }
1262 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001263 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001264 }
1265};
1266
Chris Lattner86102b82005-01-01 16:22:27 +00001267static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +00001268 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +00001269 if (isa<CastInst>(I)) {
1270 if (Constant *SOC = dyn_cast<Constant>(SO))
1271 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +00001272
Chris Lattner86102b82005-01-01 16:22:27 +00001273 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1274 SO->getName() + ".cast"), I);
1275 }
1276
Chris Lattner183b3362004-04-09 19:05:30 +00001277 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +00001278 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1279 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +00001280
Chris Lattner183b3362004-04-09 19:05:30 +00001281 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1282 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +00001283 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1284 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +00001285 }
1286
1287 Value *Op0 = SO, *Op1 = ConstOperand;
1288 if (!ConstIsRHS)
1289 std::swap(Op0, Op1);
1290 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +00001291 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1292 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1293 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1294 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001295 else {
Chris Lattner183b3362004-04-09 19:05:30 +00001296 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +00001297 abort();
1298 }
Chris Lattner86102b82005-01-01 16:22:27 +00001299 return IC->InsertNewInstBefore(New, I);
1300}
1301
1302// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1303// constant as the other operand, try to fold the binary operator into the
1304// select arguments. This also works for Cast instructions, which obviously do
1305// not have a second operand.
1306static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1307 InstCombiner *IC) {
1308 // Don't modify shared select instructions
1309 if (!SI->hasOneUse()) return 0;
1310 Value *TV = SI->getOperand(1);
1311 Value *FV = SI->getOperand(2);
1312
1313 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +00001314 // Bool selects with constant operands can be folded to logical ops.
1315 if (SI->getType() == Type::BoolTy) return 0;
1316
Chris Lattner86102b82005-01-01 16:22:27 +00001317 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1318 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1319
1320 return new SelectInst(SI->getCondition(), SelectTrueVal,
1321 SelectFalseVal);
1322 }
1323 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +00001324}
1325
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001326
1327/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1328/// node as operand #0, see if we can fold the instruction into the PHI (which
1329/// is only possible if all operands to the PHI are constants).
1330Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1331 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00001332 unsigned NumPHIValues = PN->getNumIncomingValues();
1333 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1334 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001335
1336 // Check to see if all of the operands of the PHI are constants. If not, we
1337 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +00001338 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001339 if (!isa<Constant>(PN->getIncomingValue(i)))
1340 return 0;
1341
1342 // Okay, we can do the transformation: create the new PHI node.
1343 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1344 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +00001345 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001346 InsertNewInstBefore(NewPN, *PN);
1347
1348 // Next, add all of the operands to the PHI.
1349 if (I.getNumOperands() == 2) {
1350 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +00001351 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001352 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1353 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1354 PN->getIncomingBlock(i));
1355 }
1356 } else {
1357 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1358 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +00001359 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001360 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1361 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1362 PN->getIncomingBlock(i));
1363 }
1364 }
1365 return ReplaceInstUsesWith(I, NewPN);
1366}
1367
Chris Lattner113f4f42002-06-25 16:13:24 +00001368Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001369 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001370 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001371
Chris Lattnercf4a9962004-04-10 22:01:55 +00001372 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +00001373 // X + undef -> undef
1374 if (isa<UndefValue>(RHS))
1375 return ReplaceInstUsesWith(I, RHS);
1376
Chris Lattnercf4a9962004-04-10 22:01:55 +00001377 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +00001378 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1379 if (RHSC->isNullValue())
1380 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +00001381 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1382 if (CFP->isExactlyValue(-0.0))
1383 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +00001384 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001385
Chris Lattnercf4a9962004-04-10 22:01:55 +00001386 // X + (signbit) --> X ^ signbit
1387 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner92a68652006-02-07 08:05:22 +00001388 uint64_t Val = CI->getZExtValue();
Chris Lattner77defba2006-02-07 07:00:41 +00001389 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001390 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +00001391 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001392
1393 if (isa<PHINode>(LHS))
1394 if (Instruction *NV = FoldOpIntoPhi(I))
1395 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001396
Chris Lattner330628a2006-01-06 17:59:59 +00001397 ConstantInt *XorRHS = 0;
1398 Value *XorLHS = 0;
Chris Lattner0b3557f2005-09-24 23:43:33 +00001399 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1400 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1401 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1402 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1403
1404 uint64_t C0080Val = 1ULL << 31;
1405 int64_t CFF80Val = -C0080Val;
1406 unsigned Size = 32;
1407 do {
1408 if (TySizeBits > Size) {
1409 bool Found = false;
1410 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1411 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1412 if (RHSSExt == CFF80Val) {
1413 if (XorRHS->getZExtValue() == C0080Val)
1414 Found = true;
1415 } else if (RHSZExt == C0080Val) {
1416 if (XorRHS->getSExtValue() == CFF80Val)
1417 Found = true;
1418 }
1419 if (Found) {
1420 // This is a sign extend if the top bits are known zero.
Chris Lattner4534dd592006-02-09 07:38:58 +00001421 uint64_t Mask = ~0ULL;
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001422 Mask <<= 64-(TySizeBits-Size);
Chris Lattner4534dd592006-02-09 07:38:58 +00001423 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001424 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner0b3557f2005-09-24 23:43:33 +00001425 Size = 0; // Not a sign ext, but can't be any others either.
1426 goto FoundSExt;
1427 }
1428 }
1429 Size >>= 1;
1430 C0080Val >>= Size;
1431 CFF80Val >>= Size;
1432 } while (Size >= 8);
1433
1434FoundSExt:
1435 const Type *MiddleType = 0;
1436 switch (Size) {
1437 default: break;
1438 case 32: MiddleType = Type::IntTy; break;
1439 case 16: MiddleType = Type::ShortTy; break;
1440 case 8: MiddleType = Type::SByteTy; break;
1441 }
1442 if (MiddleType) {
1443 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1444 InsertNewInstBefore(NewTrunc, I);
1445 return new CastInst(NewTrunc, I.getType());
1446 }
1447 }
Chris Lattnercf4a9962004-04-10 22:01:55 +00001448 }
Chris Lattner9fa53de2002-05-06 16:49:18 +00001449
Chris Lattnerb8b97502003-08-13 19:01:45 +00001450 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001451 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +00001452 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +00001453
1454 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1455 if (RHSI->getOpcode() == Instruction::Sub)
1456 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1457 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1458 }
1459 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1460 if (LHSI->getOpcode() == Instruction::Sub)
1461 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1462 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1463 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001464 }
Chris Lattnerede3fe02003-08-13 04:18:28 +00001465
Chris Lattner147e9752002-05-08 22:46:53 +00001466 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +00001467 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001468 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001469
1470 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +00001471 if (!isa<Constant>(RHS))
1472 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001473 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +00001474
Misha Brukmanb1c93172005-04-21 23:48:37 +00001475
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001476 ConstantInt *C2;
1477 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1478 if (X == RHS) // X*C + X --> X * (C+1)
1479 return BinaryOperator::createMul(RHS, AddOne(C2));
1480
1481 // X*C1 + X*C2 --> X * (C1+C2)
1482 ConstantInt *C1;
1483 if (X == dyn_castFoldableMul(RHS, C1))
1484 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +00001485 }
1486
1487 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001488 if (dyn_castFoldableMul(RHS, C2) == LHS)
1489 return BinaryOperator::createMul(LHS, AddOne(C2));
1490
Chris Lattner57c8d992003-02-18 19:57:07 +00001491
Chris Lattnerb8b97502003-08-13 19:01:45 +00001492 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001493 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +00001494 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +00001495
Chris Lattnerb9cde762003-10-02 15:11:26 +00001496 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner330628a2006-01-06 17:59:59 +00001497 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001498 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1499 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1500 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +00001501 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00001502
Chris Lattnerbff91d92004-10-08 05:07:56 +00001503 // (X & FF00) + xx00 -> (X+xx00) & FF00
1504 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1505 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1506 if (Anded == CRHS) {
1507 // See if all bits from the first bit set in the Add RHS up are included
1508 // in the mask. First, get the rightmost bit.
1509 uint64_t AddRHSV = CRHS->getRawValue();
1510
1511 // Form a mask of all bits from the lowest bit added through the top.
1512 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner77defba2006-02-07 07:00:41 +00001513 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerbff91d92004-10-08 05:07:56 +00001514
1515 // See if the and mask includes all of these bits.
1516 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001517
Chris Lattnerbff91d92004-10-08 05:07:56 +00001518 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1519 // Okay, the xform is safe. Insert the new add pronto.
1520 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1521 LHS->getName()), I);
1522 return BinaryOperator::createAnd(NewAdd, C2);
1523 }
1524 }
1525 }
1526
Chris Lattnerd4252a72004-07-30 07:50:03 +00001527 // Try to fold constant add into select arguments.
1528 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +00001529 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +00001530 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +00001531 }
1532
Chris Lattner113f4f42002-06-25 16:13:24 +00001533 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001534}
1535
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001536// isSignBit - Return true if the value represented by the constant only has the
1537// highest order bit set.
1538static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001539 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +00001540 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001541}
1542
Chris Lattner022167f2004-03-13 00:11:49 +00001543/// RemoveNoopCast - Strip off nonconverting casts from the value.
1544///
1545static Value *RemoveNoopCast(Value *V) {
1546 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1547 const Type *CTy = CI->getType();
1548 const Type *OpTy = CI->getOperand(0)->getType();
1549 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001550 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +00001551 return RemoveNoopCast(CI->getOperand(0));
1552 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1553 return RemoveNoopCast(CI->getOperand(0));
1554 }
1555 return V;
1556}
1557
Chris Lattner113f4f42002-06-25 16:13:24 +00001558Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001559 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001560
Chris Lattnere6794492002-08-12 21:17:25 +00001561 if (Op0 == Op1) // sub X, X -> 0
1562 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +00001563
Chris Lattnere6794492002-08-12 21:17:25 +00001564 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +00001565 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001566 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +00001567
Chris Lattner81a7a232004-10-16 18:11:37 +00001568 if (isa<UndefValue>(Op0))
1569 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1570 if (isa<UndefValue>(Op1))
1571 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1572
Chris Lattner8f2f5982003-11-05 01:06:05 +00001573 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1574 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001575 if (C->isAllOnesValue())
1576 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +00001577
Chris Lattner8f2f5982003-11-05 01:06:05 +00001578 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001579 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00001580 if (match(Op1, m_Not(m_Value(X))))
1581 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001582 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +00001583 // -((uint)X >> 31) -> ((int)X >> 31)
1584 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +00001585 if (C->isNullValue()) {
1586 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1587 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +00001588 if (SI->getOpcode() == Instruction::Shr)
1589 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1590 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +00001591 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +00001592 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001593 else
Chris Lattner97bfcea2004-06-17 18:16:02 +00001594 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +00001595 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001596 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +00001597 // Ok, the transformation is safe. Insert a cast of the incoming
1598 // value, then the new shift, then the new cast.
1599 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1600 SI->getOperand(0)->getName());
1601 Value *InV = InsertNewInstBefore(FirstCast, I);
1602 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1603 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +00001604 if (NewShift->getType() == I.getType())
1605 return NewShift;
1606 else {
1607 InV = InsertNewInstBefore(NewShift, I);
1608 return new CastInst(NewShift, I.getType());
1609 }
Chris Lattner92295c52004-03-12 23:53:13 +00001610 }
1611 }
Chris Lattner022167f2004-03-13 00:11:49 +00001612 }
Chris Lattner183b3362004-04-09 19:05:30 +00001613
1614 // Try to fold constant sub into select arguments.
1615 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00001616 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001617 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001618
1619 if (isa<PHINode>(Op0))
1620 if (Instruction *NV = FoldOpIntoPhi(I))
1621 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +00001622 }
1623
Chris Lattnera9be4492005-04-07 16:15:25 +00001624 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1625 if (Op1I->getOpcode() == Instruction::Add &&
1626 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001627 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001628 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001629 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +00001630 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +00001631 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1632 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1633 // C1-(X+C2) --> (C1-C2)-X
1634 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1635 Op1I->getOperand(0));
1636 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001637 }
1638
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001639 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001640 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1641 // is not used by anyone else...
1642 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +00001643 if (Op1I->getOpcode() == Instruction::Sub &&
1644 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001645 // Swap the two operands of the subexpr...
1646 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1647 Op1I->setOperand(0, IIOp1);
1648 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001649
Chris Lattner3082c5a2003-02-18 19:28:33 +00001650 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001651 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001652 }
1653
1654 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1655 //
1656 if (Op1I->getOpcode() == Instruction::And &&
1657 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1658 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1659
Chris Lattner396dbfe2004-06-09 05:08:07 +00001660 Value *NewNot =
1661 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001662 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001663 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001664
Chris Lattner0aee4b72004-10-06 15:08:25 +00001665 // -(X sdiv C) -> (X sdiv -C)
1666 if (Op1I->getOpcode() == Instruction::Div)
1667 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +00001668 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +00001669 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001670 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +00001671 ConstantExpr::getNeg(DivRHS));
1672
Chris Lattner57c8d992003-02-18 19:57:07 +00001673 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +00001674 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001675 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001676 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001677 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001678 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001679 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001680 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001681 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001682
Chris Lattner47060462005-04-07 17:14:51 +00001683 if (!Op0->getType()->isFloatingPoint())
1684 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1685 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001686 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1687 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1688 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1689 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001690 } else if (Op0I->getOpcode() == Instruction::Sub) {
1691 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1692 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001693 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001694
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001695 ConstantInt *C1;
1696 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1697 if (X == Op1) { // X*C - X --> X * (C-1)
1698 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1699 return BinaryOperator::createMul(Op1, CP1);
1700 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001701
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001702 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1703 if (X == dyn_castFoldableMul(Op1, C2))
1704 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1705 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001706 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001707}
1708
Chris Lattnere79e8542004-02-23 06:38:22 +00001709/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1710/// really just returns true if the most significant (sign) bit is set.
1711static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1712 if (RHS->getType()->isSigned()) {
1713 // True if source is LHS < 0 or LHS <= -1
1714 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1715 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1716 } else {
1717 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1718 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1719 // the size of the integer type.
1720 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001721 return RHSC->getValue() ==
1722 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001723 if (Opcode == Instruction::SetGT)
1724 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001725 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001726 }
1727 return false;
1728}
1729
Chris Lattner113f4f42002-06-25 16:13:24 +00001730Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001731 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001732 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001733
Chris Lattner81a7a232004-10-16 18:11:37 +00001734 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1735 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1736
Chris Lattnere6794492002-08-12 21:17:25 +00001737 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001738 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1739 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001740
1741 // ((X << C1)*C2) == (X * (C2 << C1))
1742 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1743 if (SI->getOpcode() == Instruction::Shl)
1744 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001745 return BinaryOperator::createMul(SI->getOperand(0),
1746 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001747
Chris Lattnercce81be2003-09-11 22:24:54 +00001748 if (CI->isNullValue())
1749 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1750 if (CI->equalsInt(1)) // X * 1 == X
1751 return ReplaceInstUsesWith(I, Op0);
1752 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001753 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001754
Chris Lattnercce81be2003-09-11 22:24:54 +00001755 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001756 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1757 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001758 return new ShiftInst(Instruction::Shl, Op0,
1759 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001760 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001761 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001762 if (Op1F->isNullValue())
1763 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001764
Chris Lattner3082c5a2003-02-18 19:28:33 +00001765 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1766 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1767 if (Op1F->getValue() == 1.0)
1768 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1769 }
Chris Lattner32c01df2006-03-04 06:04:02 +00001770
1771 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1772 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1773 isa<ConstantInt>(Op0I->getOperand(1))) {
1774 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1775 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1776 Op1, "tmp");
1777 InsertNewInstBefore(Add, I);
1778 Value *C1C2 = ConstantExpr::getMul(Op1,
1779 cast<Constant>(Op0I->getOperand(1)));
1780 return BinaryOperator::createAdd(Add, C1C2);
1781
1782 }
Chris Lattner183b3362004-04-09 19:05:30 +00001783
1784 // Try to fold constant mul into select arguments.
1785 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001786 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001787 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001788
1789 if (isa<PHINode>(Op0))
1790 if (Instruction *NV = FoldOpIntoPhi(I))
1791 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001792 }
1793
Chris Lattner934a64cf2003-03-10 23:23:04 +00001794 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1795 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001796 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001797
Chris Lattner2635b522004-02-23 05:39:21 +00001798 // If one of the operands of the multiply is a cast from a boolean value, then
1799 // we know the bool is either zero or one, so this is a 'masking' multiply.
1800 // See if we can simplify things based on how the boolean was originally
1801 // formed.
1802 CastInst *BoolCast = 0;
1803 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1804 if (CI->getOperand(0)->getType() == Type::BoolTy)
1805 BoolCast = CI;
1806 if (!BoolCast)
1807 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1808 if (CI->getOperand(0)->getType() == Type::BoolTy)
1809 BoolCast = CI;
1810 if (BoolCast) {
1811 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1812 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1813 const Type *SCOpTy = SCIOp0->getType();
1814
Chris Lattnere79e8542004-02-23 06:38:22 +00001815 // If the setcc is true iff the sign bit of X is set, then convert this
1816 // multiply into a shift/and combination.
1817 if (isa<ConstantInt>(SCIOp1) &&
1818 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001819 // Shift the X value right to turn it into "all signbits".
1820 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001821 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001822 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001823 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001824 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1825 SCIOp0->getName()), I);
1826 }
1827
1828 Value *V =
1829 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1830 BoolCast->getOperand(0)->getName()+
1831 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001832
1833 // If the multiply type is not the same as the source type, sign extend
1834 // or truncate to the multiply type.
1835 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001836 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001837
Chris Lattner2635b522004-02-23 05:39:21 +00001838 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001839 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001840 }
1841 }
1842 }
1843
Chris Lattner113f4f42002-06-25 16:13:24 +00001844 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001845}
1846
Chris Lattner113f4f42002-06-25 16:13:24 +00001847Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001849
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001850 if (isa<UndefValue>(Op0)) // undef / X -> 0
1851 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1852 if (isa<UndefValue>(Op1))
1853 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1854
1855 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001856 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001857 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001858 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001859
Chris Lattnere20c3342004-04-26 14:01:59 +00001860 // div X, -1 == -X
1861 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001862 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001863
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001864 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001865 if (LHS->getOpcode() == Instruction::Div)
1866 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001867 // (X / C1) / C2 -> X / (C1*C2)
1868 return BinaryOperator::createDiv(LHS->getOperand(0),
1869 ConstantExpr::getMul(RHS, LHSRHS));
1870 }
1871
Chris Lattner3082c5a2003-02-18 19:28:33 +00001872 // Check to see if this is an unsigned division with an exact power of 2,
1873 // if so, convert to a right shift.
1874 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1875 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001876 if (isPowerOf2_64(Val)) {
1877 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001878 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001879 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001880 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001881
Chris Lattner4ad08352004-10-09 02:50:40 +00001882 // -X/C -> X/-C
1883 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001884 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001885 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1886
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001887 if (!RHS->isNullValue()) {
1888 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001889 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001890 return R;
1891 if (isa<PHINode>(Op0))
1892 if (Instruction *NV = FoldOpIntoPhi(I))
1893 return NV;
1894 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001895 }
1896
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001897 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1898 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1899 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1900 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1901 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1902 if (STO->getValue() == 0) { // Couldn't be this argument.
1903 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001904 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001905 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001906 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001907 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001908 }
1909
Chris Lattner42362612005-04-08 04:03:26 +00001910 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001911 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1912 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001913 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1914 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1915 TC, SI->getName()+".t");
1916 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001917
Chris Lattner42362612005-04-08 04:03:26 +00001918 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1919 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1920 FC, SI->getName()+".f");
1921 FSI = InsertNewInstBefore(FSI, I);
1922 return new SelectInst(SI->getOperand(0), TSI, FSI);
1923 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001924 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001925
Chris Lattner3082c5a2003-02-18 19:28:33 +00001926 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001927 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001928 if (LHS->equalsInt(0))
1929 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1930
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001931 if (I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001932 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001933 // unsigned inputs), turn this into a udiv.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00001934 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1935 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001936 const Type *NTy = Op0->getType()->getUnsignedVersion();
1937 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1938 InsertNewInstBefore(LHS, I);
1939 Value *RHS;
1940 if (Constant *R = dyn_cast<Constant>(Op1))
1941 RHS = ConstantExpr::getCast(R, NTy);
1942 else
1943 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1944 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1945 InsertNewInstBefore(Div, I);
1946 return new CastInst(Div, I.getType());
1947 }
Chris Lattner2e90b732006-02-05 07:54:04 +00001948 } else {
1949 // Known to be an unsigned division.
1950 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1951 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1952 if (RHSI->getOpcode() == Instruction::Shl &&
1953 isa<ConstantUInt>(RHSI->getOperand(0))) {
1954 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1955 if (isPowerOf2_64(C1)) {
1956 unsigned C2 = Log2_64(C1);
1957 Value *Add = RHSI->getOperand(1);
1958 if (C2) {
1959 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1960 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1961 "tmp"), I);
1962 }
1963 return new ShiftInst(Instruction::Shr, Op0, Add);
1964 }
1965 }
1966 }
Chris Lattnerdd0c1742005-11-05 07:40:31 +00001967 }
1968
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001969 return 0;
1970}
1971
1972
Chris Lattner85dda9a2006-03-02 06:50:58 +00001973/// GetFactor - If we can prove that the specified value is at least a multiple
1974/// of some factor, return that factor.
1975static Constant *GetFactor(Value *V) {
1976 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1977 return CI;
1978
1979 // Unless we can be tricky, we know this is a multiple of 1.
1980 Constant *Result = ConstantInt::get(V->getType(), 1);
1981
1982 Instruction *I = dyn_cast<Instruction>(V);
1983 if (!I) return Result;
1984
1985 if (I->getOpcode() == Instruction::Mul) {
1986 // Handle multiplies by a constant, etc.
1987 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1988 GetFactor(I->getOperand(1)));
1989 } else if (I->getOpcode() == Instruction::Shl) {
1990 // (X<<C) -> X * (1 << C)
1991 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1992 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1993 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1994 }
1995 } else if (I->getOpcode() == Instruction::And) {
1996 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1997 // X & 0xFFF0 is known to be a multiple of 16.
1998 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1999 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2000 return ConstantExpr::getShl(Result,
2001 ConstantUInt::get(Type::UByteTy, Zeros));
2002 }
2003 } else if (I->getOpcode() == Instruction::Cast) {
2004 Value *Op = I->getOperand(0);
2005 // Only handle int->int casts.
2006 if (!Op->getType()->isInteger()) return Result;
2007 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2008 }
2009 return Result;
2010}
2011
Chris Lattner113f4f42002-06-25 16:13:24 +00002012Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002014
2015 // 0 % X == 0, we don't need to preserve faults!
2016 if (Constant *LHS = dyn_cast<Constant>(Op0))
2017 if (LHS->isNullValue())
2018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2019
2020 if (isa<UndefValue>(Op0)) // undef % X -> 0
2021 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2022 if (isa<UndefValue>(Op1))
2023 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2024
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002025 if (I.getType()->isSigned()) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002026 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00002027 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00002028 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00002029 // X % -Y -> X % Y
2030 AddUsesToWorkList(I);
2031 I.setOperand(1, RHSNeg);
2032 return &I;
2033 }
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002034
2035 // If the top bits of both operands are zero (i.e. we can prove they are
2036 // unsigned inputs), turn this into a urem.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002037 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2038 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnere9ff0ea2005-11-05 07:28:37 +00002039 const Type *NTy = Op0->getType()->getUnsignedVersion();
2040 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2041 InsertNewInstBefore(LHS, I);
2042 Value *RHS;
2043 if (Constant *R = dyn_cast<Constant>(Op1))
2044 RHS = ConstantExpr::getCast(R, NTy);
2045 else
2046 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2047 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2048 InsertNewInstBefore(Rem, I);
2049 return new CastInst(Rem, I.getType());
2050 }
2051 }
Chris Lattner7fd5f072004-07-06 07:01:22 +00002052
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002053 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002054 // X % 0 == undef, we don't need to preserve faults!
2055 if (RHS->equalsInt(0))
2056 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2057
Chris Lattner3082c5a2003-02-18 19:28:33 +00002058 if (RHS->equalsInt(1)) // X % 1 == 0
2059 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2060
2061 // Check to see if this is an unsigned remainder with an exact power of 2,
2062 // if so, convert to a bitwise and.
2063 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002064 if (isPowerOf2_64(C->getValue()))
2065 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00002066
Chris Lattnerb70f1412006-02-28 05:49:21 +00002067 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2068 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2069 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2070 return R;
2071 } else if (isa<PHINode>(Op0I)) {
2072 if (Instruction *NV = FoldOpIntoPhi(I))
2073 return NV;
Chris Lattnerb70f1412006-02-28 05:49:21 +00002074 }
Chris Lattner85dda9a2006-03-02 06:50:58 +00002075
2076 // X*C1%C2 --> 0 iff C1%C2 == 0
2077 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2078 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerb70f1412006-02-28 05:49:21 +00002079 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002080 }
2081
Chris Lattner2e90b732006-02-05 07:54:04 +00002082 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2083 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2084 if (I.getType()->isUnsigned() &&
2085 RHSI->getOpcode() == Instruction::Shl &&
2086 isa<ConstantUInt>(RHSI->getOperand(0))) {
2087 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2088 if (isPowerOf2_64(C1)) {
2089 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2090 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2091 "tmp"), I);
2092 return BinaryOperator::createAnd(Op0, Add);
2093 }
2094 }
Chris Lattner0de4a8d2006-02-28 05:30:45 +00002095
2096 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2097 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2098 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2099 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2100 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2101 if (STO->getValue() == 0) { // Couldn't be this argument.
2102 I.setOperand(1, SFO);
2103 return &I;
2104 } else if (SFO->getValue() == 0) {
2105 I.setOperand(1, STO);
2106 return &I;
2107 }
2108
2109 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2110 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2111 SubOne(STO), SI->getName()+".t"), I);
2112 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2113 SubOne(SFO), SI->getName()+".f"), I);
2114 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2115 }
2116 }
Chris Lattner2e90b732006-02-05 07:54:04 +00002117 }
2118
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002119 return 0;
2120}
2121
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002122// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00002123static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner77defba2006-02-07 07:00:41 +00002124 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2125 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002126
2127 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002128
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002129 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002130 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002131 int64_t Val = INT64_MAX; // All ones
2132 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2133 return CS->getValue() == Val-1;
2134}
2135
2136// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00002137static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002138 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2139 return CU->getValue() == 1;
2140
2141 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002142
2143 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002144 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002145 int64_t Val = -1; // All ones
2146 Val <<= TypeBits-1; // Shift over to the right spot
2147 return CS->getValue() == Val+1;
2148}
2149
Chris Lattner35167c32004-06-09 07:59:58 +00002150// isOneBitSet - Return true if there is exactly one bit set in the specified
2151// constant.
2152static bool isOneBitSet(const ConstantInt *CI) {
2153 uint64_t V = CI->getRawValue();
2154 return V && (V & (V-1)) == 0;
2155}
2156
Chris Lattner8fc5af42004-09-23 21:46:38 +00002157#if 0 // Currently unused
2158// isLowOnes - Return true if the constant is of the form 0+1+.
2159static bool isLowOnes(const ConstantInt *CI) {
2160 uint64_t V = CI->getRawValue();
2161
2162 // There won't be bits set in parts that the type doesn't contain.
2163 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2164
2165 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2166 return U && V && (U & V) == 0;
2167}
2168#endif
2169
2170// isHighOnes - Return true if the constant is of the form 1+0+.
2171// This is the same as lowones(~X).
2172static bool isHighOnes(const ConstantInt *CI) {
2173 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00002174 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00002175
2176 // There won't be bits set in parts that the type doesn't contain.
2177 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2178
2179 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2180 return U && V && (U & V) == 0;
2181}
2182
2183
Chris Lattner3ac7c262003-08-13 20:16:26 +00002184/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2185/// are carefully arranged to allow folding of expressions such as:
2186///
2187/// (A < B) | (A > B) --> (A != B)
2188///
2189/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2190/// represents that the comparison is true if A == B, and bit value '1' is true
2191/// if A < B.
2192///
2193static unsigned getSetCondCode(const SetCondInst *SCI) {
2194 switch (SCI->getOpcode()) {
2195 // False -> 0
2196 case Instruction::SetGT: return 1;
2197 case Instruction::SetEQ: return 2;
2198 case Instruction::SetGE: return 3;
2199 case Instruction::SetLT: return 4;
2200 case Instruction::SetNE: return 5;
2201 case Instruction::SetLE: return 6;
2202 // True -> 7
2203 default:
2204 assert(0 && "Invalid SetCC opcode!");
2205 return 0;
2206 }
2207}
2208
2209/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2210/// opcode and two operands into either a constant true or false, or a brand new
2211/// SetCC instruction.
2212static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2213 switch (Opcode) {
2214 case 0: return ConstantBool::False;
2215 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2216 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2217 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2218 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2219 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2220 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2221 case 7: return ConstantBool::True;
2222 default: assert(0 && "Illegal SetCCCode!"); return 0;
2223 }
2224}
2225
2226// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2227struct FoldSetCCLogical {
2228 InstCombiner &IC;
2229 Value *LHS, *RHS;
2230 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2231 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2232 bool shouldApply(Value *V) const {
2233 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2234 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2235 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2236 return false;
2237 }
2238 Instruction *apply(BinaryOperator &Log) const {
2239 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2240 if (SCI->getOperand(0) != LHS) {
2241 assert(SCI->getOperand(1) == LHS);
2242 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2243 }
2244
2245 unsigned LHSCode = getSetCondCode(SCI);
2246 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2247 unsigned Code;
2248 switch (Log.getOpcode()) {
2249 case Instruction::And: Code = LHSCode & RHSCode; break;
2250 case Instruction::Or: Code = LHSCode | RHSCode; break;
2251 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00002252 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00002253 }
2254
2255 Value *RV = getSetCCValue(Code, LHS, RHS);
2256 if (Instruction *I = dyn_cast<Instruction>(RV))
2257 return I;
2258 // Otherwise, it's a constant boolean value...
2259 return IC.ReplaceInstUsesWith(Log, RV);
2260 }
2261};
2262
Chris Lattnerba1cb382003-09-19 17:17:26 +00002263// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2264// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2265// guaranteed to be either a shift instruction or a binary operator.
2266Instruction *InstCombiner::OptAndOp(Instruction *Op,
2267 ConstantIntegral *OpRHS,
2268 ConstantIntegral *AndRHS,
2269 BinaryOperator &TheAnd) {
2270 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00002271 Constant *Together = 0;
2272 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002273 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002274
Chris Lattnerba1cb382003-09-19 17:17:26 +00002275 switch (Op->getOpcode()) {
2276 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00002277 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002278 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2279 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002280 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002281 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002282 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002283 }
2284 break;
2285 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00002286 if (Together == AndRHS) // (X | C) & C --> C
2287 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002288
Chris Lattner86102b82005-01-01 16:22:27 +00002289 if (Op->hasOneUse() && Together != OpRHS) {
2290 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2291 std::string Op0Name = Op->getName(); Op->setName("");
2292 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2293 InsertNewInstBefore(Or, TheAnd);
2294 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002295 }
2296 break;
2297 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002298 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002299 // Adding a one to a single bit bit-field should be turned into an XOR
2300 // of the bit. First thing to check is to see if this AND is with a
2301 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00002302 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002303
2304 // Clear bits that are not part of the constant.
Chris Lattner77defba2006-02-07 07:00:41 +00002305 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerba1cb382003-09-19 17:17:26 +00002306
2307 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00002308 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00002309 // Ok, at this point, we know that we are masking the result of the
2310 // ADD down to exactly one bit. If the constant we are adding has
2311 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00002312 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002313
Chris Lattnerba1cb382003-09-19 17:17:26 +00002314 // Check to see if any bits below the one bit set in AndRHSV are set.
2315 if ((AddRHS & (AndRHSV-1)) == 0) {
2316 // If not, the only thing that can effect the output of the AND is
2317 // the bit specified by AndRHSV. If that bit is set, the effect of
2318 // the XOR is to toggle the bit. If it is clear, then the ADD has
2319 // no effect.
2320 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2321 TheAnd.setOperand(0, X);
2322 return &TheAnd;
2323 } else {
2324 std::string Name = Op->getName(); Op->setName("");
2325 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002326 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002327 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002328 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00002329 }
2330 }
2331 }
2332 }
2333 break;
Chris Lattner2da29172003-09-19 19:05:02 +00002334
2335 case Instruction::Shl: {
2336 // We know that the AND will not produce any of the bits shifted in, so if
2337 // the anded constant includes them, clear them now!
2338 //
2339 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002340 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2341 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002342
Chris Lattner7e794272004-09-24 15:21:34 +00002343 if (CI == ShlMask) { // Masking out bits that the shift already masks
2344 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2345 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00002346 TheAnd.setOperand(1, CI);
2347 return &TheAnd;
2348 }
2349 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002350 }
Chris Lattner2da29172003-09-19 19:05:02 +00002351 case Instruction::Shr:
2352 // We know that the AND will not produce any of the bits shifted in, so if
2353 // the anded constant includes them, clear them now! This only applies to
2354 // unsigned shifts, because a signed shr may bring in set bits!
2355 //
2356 if (AndRHS->getType()->isUnsigned()) {
2357 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00002358 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2359 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2360
2361 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2362 return ReplaceInstUsesWith(TheAnd, Op);
2363 } else if (CI != AndRHS) {
2364 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00002365 return &TheAnd;
2366 }
Chris Lattner7e794272004-09-24 15:21:34 +00002367 } else { // Signed shr.
2368 // See if this is shifting in some sign extension, then masking it out
2369 // with an and.
2370 if (Op->hasOneUse()) {
2371 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2372 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2373 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00002374 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00002375 // Make the argument unsigned.
2376 Value *ShVal = Op->getOperand(0);
2377 ShVal = InsertCastBefore(ShVal,
2378 ShVal->getType()->getUnsignedVersion(),
2379 TheAnd);
2380 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2381 OpRHS, Op->getName()),
2382 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00002383 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2384 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2385 TheAnd.getName()),
2386 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00002387 return new CastInst(ShVal, Op->getType());
2388 }
2389 }
Chris Lattner2da29172003-09-19 19:05:02 +00002390 }
2391 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00002392 }
2393 return 0;
2394}
2395
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002396
Chris Lattner6862fbd2004-09-29 17:40:11 +00002397/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2398/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2399/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2400/// insert new instructions.
2401Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2402 bool Inside, Instruction &IB) {
2403 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2404 "Lo is not <= Hi in range emission code!");
2405 if (Inside) {
2406 if (Lo == Hi) // Trivially false.
2407 return new SetCondInst(Instruction::SetNE, V, V);
2408 if (cast<ConstantIntegral>(Lo)->isMinValue())
2409 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002410
Chris Lattner6862fbd2004-09-29 17:40:11 +00002411 Constant *AddCST = ConstantExpr::getNeg(Lo);
2412 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2413 InsertNewInstBefore(Add, IB);
2414 // Convert to unsigned for the comparison.
2415 const Type *UnsType = Add->getType()->getUnsignedVersion();
2416 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2417 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2418 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2419 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2420 }
2421
2422 if (Lo == Hi) // Trivially true.
2423 return new SetCondInst(Instruction::SetEQ, V, V);
2424
2425 Hi = SubOne(cast<ConstantInt>(Hi));
2426 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2427 return new SetCondInst(Instruction::SetGT, V, Hi);
2428
2429 // Emit X-Lo > Hi-Lo-1
2430 Constant *AddCST = ConstantExpr::getNeg(Lo);
2431 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2432 InsertNewInstBefore(Add, IB);
2433 // Convert to unsigned for the comparison.
2434 const Type *UnsType = Add->getType()->getUnsignedVersion();
2435 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2436 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2437 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2438 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2439}
2440
Chris Lattnerb4b25302005-09-18 07:22:02 +00002441// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2442// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2443// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2444// not, since all 1s are not contiguous.
2445static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2446 uint64_t V = Val->getRawValue();
2447 if (!isShiftedMask_64(V)) return false;
2448
2449 // look for the first zero bit after the run of ones
2450 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2451 // look for the first non-zero bit
2452 ME = 64-CountLeadingZeros_64(V);
2453 return true;
2454}
2455
2456
2457
2458/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2459/// where isSub determines whether the operator is a sub. If we can fold one of
2460/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00002461///
2462/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2463/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2464/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2465///
2466/// return (A +/- B).
2467///
2468Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2469 ConstantIntegral *Mask, bool isSub,
2470 Instruction &I) {
2471 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2472 if (!LHSI || LHSI->getNumOperands() != 2 ||
2473 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2474
2475 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2476
2477 switch (LHSI->getOpcode()) {
2478 default: return 0;
2479 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002480 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2481 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2482 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2483 break;
2484
2485 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2486 // part, we don't need any explicit masks to take them out of A. If that
2487 // is all N is, ignore it.
2488 unsigned MB, ME;
2489 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002490 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2491 Mask >>= 64-MB+1;
2492 if (MaskedValueIsZero(RHS, Mask))
Chris Lattnerb4b25302005-09-18 07:22:02 +00002493 break;
2494 }
2495 }
Chris Lattneraf517572005-09-18 04:24:45 +00002496 return 0;
2497 case Instruction::Or:
2498 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002499 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2500 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2501 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00002502 break;
2503 return 0;
2504 }
2505
2506 Instruction *New;
2507 if (isSub)
2508 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2509 else
2510 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2511 return InsertNewInstBefore(New, I);
2512}
2513
Chris Lattner113f4f42002-06-25 16:13:24 +00002514Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002515 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002516 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002517
Chris Lattner81a7a232004-10-16 18:11:37 +00002518 if (isa<UndefValue>(Op1)) // X & undef -> 0
2519 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2520
Chris Lattner86102b82005-01-01 16:22:27 +00002521 // and X, X = X
2522 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002523 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002524
Chris Lattner5b2edb12006-02-12 08:02:11 +00002525 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner5997cf92006-02-08 03:25:32 +00002526 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00002527 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002528 if (!isa<PackedType>(I.getType()) &&
2529 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner0157e7f2006-02-11 09:31:47 +00002530 KnownZero, KnownOne))
Chris Lattner5997cf92006-02-08 03:25:32 +00002531 return &I;
2532
Chris Lattner86102b82005-01-01 16:22:27 +00002533 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002534 uint64_t AndRHSMask = AndRHS->getZExtValue();
2535 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002536 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner86102b82005-01-01 16:22:27 +00002537
Chris Lattnerba1cb382003-09-19 17:17:26 +00002538 // Optimize a variety of ((val OP C1) & C2) combinations...
2539 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2540 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00002541 Value *Op0LHS = Op0I->getOperand(0);
2542 Value *Op0RHS = Op0I->getOperand(1);
2543 switch (Op0I->getOpcode()) {
2544 case Instruction::Xor:
2545 case Instruction::Or:
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002546 // If the mask is only needed on one incoming arm, push it up.
2547 if (Op0I->hasOneUse()) {
2548 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2549 // Not masking anything out for the LHS, move to RHS.
2550 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2551 Op0RHS->getName()+".masked");
2552 InsertNewInstBefore(NewRHS, I);
2553 return BinaryOperator::create(
2554 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002555 }
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002556 if (!isa<Constant>(Op0RHS) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00002557 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2558 // Not masking anything out for the RHS, move to LHS.
2559 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2560 Op0LHS->getName()+".masked");
2561 InsertNewInstBefore(NewLHS, I);
2562 return BinaryOperator::create(
2563 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2564 }
2565 }
2566
Chris Lattner86102b82005-01-01 16:22:27 +00002567 break;
Chris Lattneraf517572005-09-18 04:24:45 +00002568 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002569 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2570 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2571 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2572 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2573 return BinaryOperator::createAnd(V, AndRHS);
2574 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2575 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00002576 break;
2577
2578 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00002579 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2580 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2581 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2582 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2583 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00002584 break;
Chris Lattner86102b82005-01-01 16:22:27 +00002585 }
2586
Chris Lattner16464b32003-07-23 19:25:52 +00002587 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00002588 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00002589 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00002590 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2591 const Type *SrcTy = CI->getOperand(0)->getType();
2592
Chris Lattner2c14cf72005-08-07 07:03:10 +00002593 // If this is an integer truncation or change from signed-to-unsigned, and
2594 // if the source is an and/or with immediate, transform it. This
2595 // frequently occurs for bitfield accesses.
2596 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2597 if (SrcTy->getPrimitiveSizeInBits() >=
2598 I.getType()->getPrimitiveSizeInBits() &&
2599 CastOp->getNumOperands() == 2)
Chris Lattnerab2dc4d2006-02-08 07:34:50 +00002600 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2c14cf72005-08-07 07:03:10 +00002601 if (CastOp->getOpcode() == Instruction::And) {
2602 // Change: and (cast (and X, C1) to T), C2
2603 // into : and (cast X to T), trunc(C1)&C2
2604 // This will folds the two ands together, which may allow other
2605 // simplifications.
2606 Instruction *NewCast =
2607 new CastInst(CastOp->getOperand(0), I.getType(),
2608 CastOp->getName()+".shrunk");
2609 NewCast = InsertNewInstBefore(NewCast, I);
2610
2611 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2612 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2613 return BinaryOperator::createAnd(NewCast, C3);
2614 } else if (CastOp->getOpcode() == Instruction::Or) {
2615 // Change: and (cast (or X, C1) to T), C2
2616 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2617 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2618 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2619 return ReplaceInstUsesWith(I, AndRHS);
2620 }
2621 }
Chris Lattner33217db2003-07-23 19:36:21 +00002622 }
Chris Lattner183b3362004-04-09 19:05:30 +00002623
2624 // Try to fold constant and into select arguments.
2625 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002626 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002627 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002628 if (isa<PHINode>(Op0))
2629 if (Instruction *NV = FoldOpIntoPhi(I))
2630 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00002631 }
2632
Chris Lattnerbb74e222003-03-10 23:06:50 +00002633 Value *Op0NotVal = dyn_castNotVal(Op0);
2634 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002635
Chris Lattner023a4832004-06-18 06:07:51 +00002636 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2637 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2638
Misha Brukman9c003d82004-07-30 12:50:08 +00002639 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00002640 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002641 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2642 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00002643 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00002644 return BinaryOperator::createNot(Or);
2645 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002646
2647 {
2648 Value *A = 0, *B = 0;
2649 ConstantInt *C1 = 0, *C2 = 0;
2650 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2651 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2652 return ReplaceInstUsesWith(I, Op1);
2653 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2654 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2655 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerdcd07922006-04-01 08:03:55 +00002656
2657 if (Op0->hasOneUse() &&
2658 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2659 if (A == Op1) { // (A^B)&A -> A&(A^B)
2660 I.swapOperands(); // Simplify below
2661 std::swap(Op0, Op1);
2662 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2663 cast<BinaryOperator>(Op0)->swapOperands();
2664 I.swapOperands(); // Simplify below
2665 std::swap(Op0, Op1);
2666 }
2667 }
2668 if (Op1->hasOneUse() &&
2669 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2670 if (B == Op0) { // B&(A^B) -> B&(B^A)
2671 cast<BinaryOperator>(Op1)->swapOperands();
2672 std::swap(A, B);
2673 }
2674 if (A == Op0) { // A&(A^B) -> A & ~B
2675 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2676 InsertNewInstBefore(NotB, I);
2677 return BinaryOperator::createAnd(A, NotB);
2678 }
2679 }
Chris Lattner8b10ab32006-02-13 23:07:23 +00002680 }
2681
Chris Lattner3082c5a2003-02-18 19:28:33 +00002682
Chris Lattner623826c2004-09-28 21:48:02 +00002683 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2684 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00002685 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2686 return R;
2687
Chris Lattner623826c2004-09-28 21:48:02 +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 Lattner623826c2004-09-28 21:48:02 +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 and'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: // (X == 13 & X == 15) -> false
2720 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2721 return ReplaceInstUsesWith(I, ConstantBool::False);
2722 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2723 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2724 return ReplaceInstUsesWith(I, LHS);
2725 }
2726 case Instruction::SetNE:
2727 switch (RHSCC) {
2728 default: assert(0 && "Unknown integer condition code!");
2729 case Instruction::SetLT:
2730 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2731 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2732 break; // (X != 13 & X < 15) -> no change
2733 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2734 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2735 return ReplaceInstUsesWith(I, RHS);
2736 case Instruction::SetNE:
2737 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2738 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2739 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2740 LHSVal->getName()+".off");
2741 InsertNewInstBefore(Add, I);
2742 const Type *UnsType = Add->getType()->getUnsignedVersion();
2743 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2744 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2745 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2746 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2747 }
2748 break; // (X != 13 & X != 15) -> no change
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 == 15) -> false
2755 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2756 return ReplaceInstUsesWith(I, ConstantBool::False);
2757 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2758 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2759 return ReplaceInstUsesWith(I, LHS);
2760 }
2761 case Instruction::SetGT:
2762 switch (RHSCC) {
2763 default: assert(0 && "Unknown integer condition code!");
2764 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2765 return ReplaceInstUsesWith(I, LHS);
2766 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2767 return ReplaceInstUsesWith(I, RHS);
2768 case Instruction::SetNE:
2769 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2770 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2771 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002772 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2773 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002774 }
2775 }
2776 }
2777 }
2778
Chris Lattner3af10532006-05-05 06:39:07 +00002779 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2780 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00002781 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00002782 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00002783 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00002784 // Only do this if the casts both really cause code to be generated.
2785 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2786 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00002787 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2788 Op1C->getOperand(0),
2789 I.getName());
2790 InsertNewInstBefore(NewOp, I);
2791 return new CastInst(NewOp, I.getType());
2792 }
2793 }
2794
Chris Lattner113f4f42002-06-25 16:13:24 +00002795 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002796}
2797
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002798/// CollectBSwapParts - Look to see if the specified value defines a single byte
2799/// in the result. If it does, and if the specified byte hasn't been filled in
2800/// yet, fill it in and return false.
2801static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2802 Instruction *I = dyn_cast<Instruction>(V);
2803 if (I == 0) return true;
2804
2805 // If this is an or instruction, it is an inner node of the bswap.
2806 if (I->getOpcode() == Instruction::Or)
2807 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2808 CollectBSwapParts(I->getOperand(1), ByteValues);
2809
2810 // If this is a shift by a constant int, and it is "24", then its operand
2811 // defines a byte. We only handle unsigned types here.
2812 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2813 // Not shifting the entire input by N-1 bytes?
2814 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2815 8*(ByteValues.size()-1))
2816 return true;
2817
2818 unsigned DestNo;
2819 if (I->getOpcode() == Instruction::Shl) {
2820 // X << 24 defines the top byte with the lowest of the input bytes.
2821 DestNo = ByteValues.size()-1;
2822 } else {
2823 // X >>u 24 defines the low byte with the highest of the input bytes.
2824 DestNo = 0;
2825 }
2826
2827 // If the destination byte value is already defined, the values are or'd
2828 // together, which isn't a bswap (unless it's an or of the same bits).
2829 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2830 return true;
2831 ByteValues[DestNo] = I->getOperand(0);
2832 return false;
2833 }
2834
2835 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2836 // don't have this.
2837 Value *Shift = 0, *ShiftLHS = 0;
2838 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2839 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2840 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2841 return true;
2842 Instruction *SI = cast<Instruction>(Shift);
2843
2844 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2845 if (ShiftAmt->getRawValue() & 7 ||
2846 ShiftAmt->getRawValue() > 8*ByteValues.size())
2847 return true;
2848
2849 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2850 unsigned DestByte;
2851 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2852 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2853 break;
2854 // Unknown mask for bswap.
2855 if (DestByte == ByteValues.size()) return true;
2856
2857 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2858 unsigned SrcByte;
2859 if (SI->getOpcode() == Instruction::Shl)
2860 SrcByte = DestByte - ShiftBytes;
2861 else
2862 SrcByte = DestByte + ShiftBytes;
2863
2864 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2865 if (SrcByte != ByteValues.size()-DestByte-1)
2866 return true;
2867
2868 // If the destination byte value is already defined, the values are or'd
2869 // together, which isn't a bswap (unless it's an or of the same bits).
2870 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
2871 return true;
2872 ByteValues[DestByte] = SI->getOperand(0);
2873 return false;
2874}
2875
2876/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2877/// If so, insert the new bswap intrinsic and return it.
2878Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
2879 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
2880 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
2881 return 0;
2882
2883 /// ByteValues - For each byte of the result, we keep track of which value
2884 /// defines each byte.
2885 std::vector<Value*> ByteValues;
2886 ByteValues.resize(I.getType()->getPrimitiveSize());
2887
2888 // Try to find all the pieces corresponding to the bswap.
2889 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
2890 CollectBSwapParts(I.getOperand(1), ByteValues))
2891 return 0;
2892
2893 // Check to see if all of the bytes come from the same value.
2894 Value *V = ByteValues[0];
2895 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2896
2897 // Check to make sure that all of the bytes come from the same value.
2898 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2899 if (ByteValues[i] != V)
2900 return 0;
2901
2902 // If they do then *success* we can turn this into a bswap. Figure out what
2903 // bswap to make it into.
2904 Module *M = I.getParent()->getParent()->getParent();
2905 const char *FnName;
2906 if (I.getType() == Type::UShortTy)
2907 FnName = "llvm.bswap.i16";
2908 else if (I.getType() == Type::UIntTy)
2909 FnName = "llvm.bswap.i32";
2910 else if (I.getType() == Type::ULongTy)
2911 FnName = "llvm.bswap.i64";
2912 else
2913 assert(0 && "Unknown integer type!");
2914 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
2915
2916 return new CallInst(F, V);
2917}
2918
2919
Chris Lattner113f4f42002-06-25 16:13:24 +00002920Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002921 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002922 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002923
Chris Lattner81a7a232004-10-16 18:11:37 +00002924 if (isa<UndefValue>(Op1))
2925 return ReplaceInstUsesWith(I, // X | undef -> -1
2926 ConstantIntegral::getAllOnesValue(I.getType()));
2927
Chris Lattner5b2edb12006-02-12 08:02:11 +00002928 // or X, X = X
2929 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00002930 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002931
Chris Lattner5b2edb12006-02-12 08:02:11 +00002932 // See if we can simplify any instructions used by the instruction whose sole
2933 // purpose is to compute bits we don't care about.
2934 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00002935 if (!isa<PackedType>(I.getType()) &&
2936 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00002937 KnownZero, KnownOne))
2938 return &I;
2939
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002940 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002941 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner330628a2006-01-06 17:59:59 +00002942 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00002943 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2944 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002945 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2946 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002947 InsertNewInstBefore(Or, I);
2948 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2949 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002950
Chris Lattnerd4252a72004-07-30 07:50:03 +00002951 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2952 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2953 std::string Op0Name = Op0->getName(); Op0->setName("");
2954 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2955 InsertNewInstBefore(Or, I);
2956 return BinaryOperator::createXor(Or,
2957 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002958 }
Chris Lattner183b3362004-04-09 19:05:30 +00002959
2960 // Try to fold constant and into select arguments.
2961 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002962 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002963 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002964 if (isa<PHINode>(Op0))
2965 if (Instruction *NV = FoldOpIntoPhi(I))
2966 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002967 }
2968
Chris Lattner330628a2006-01-06 17:59:59 +00002969 Value *A = 0, *B = 0;
2970 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattner4294cec2005-05-07 23:49:08 +00002971
2972 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2973 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2974 return ReplaceInstUsesWith(I, Op1);
2975 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2976 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2977 return ReplaceInstUsesWith(I, Op0);
2978
Chris Lattnerb7845d62006-07-10 20:25:24 +00002979 // (A | B) | C and A | (B | C) -> bswap if possible.
2980 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002981 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattnerb7845d62006-07-10 20:25:24 +00002982 match(Op1, m_Or(m_Value(), m_Value())) ||
2983 (match(Op0, m_Shift(m_Value(), m_Value())) &&
2984 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerc482a9e2006-06-15 19:07:26 +00002985 if (Instruction *BSwap = MatchBSwap(I))
2986 return BSwap;
2987 }
2988
Chris Lattnerb62f5082005-05-09 04:58:36 +00002989 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2990 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002991 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002992 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2993 Op0->setName("");
2994 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2995 }
2996
2997 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2998 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnerc3ebf402006-02-07 07:27:52 +00002999 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00003000 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3001 Op0->setName("");
3002 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3003 }
3004
Chris Lattner15212982005-09-18 03:42:07 +00003005 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00003006 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00003007 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3008
3009 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3010 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3011
3012
Chris Lattner01f56c62005-09-18 06:02:59 +00003013 // If we have: ((V + N) & C1) | (V & C2)
3014 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3015 // replace with V+N.
3016 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner330628a2006-01-06 17:59:59 +00003017 Value *V1 = 0, *V2 = 0;
Chris Lattner01f56c62005-09-18 06:02:59 +00003018 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3019 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3020 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003021 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003022 return ReplaceInstUsesWith(I, A);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003023 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003024 return ReplaceInstUsesWith(I, A);
3025 }
3026 // Or commutes, try both ways.
3027 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3028 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3029 // Add commutes, try both ways.
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003030 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003031 return ReplaceInstUsesWith(I, B);
Chris Lattnerc3ebf402006-02-07 07:27:52 +00003032 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner01f56c62005-09-18 06:02:59 +00003033 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00003034 }
3035 }
3036 }
Chris Lattner812aab72003-08-12 19:11:07 +00003037
Chris Lattnerd4252a72004-07-30 07:50:03 +00003038 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3039 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00003040 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003041 ConstantIntegral::getAllOnesValue(I.getType()));
3042 } else {
3043 A = 0;
3044 }
Chris Lattner4294cec2005-05-07 23:49:08 +00003045 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00003046 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3047 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00003048 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00003049 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00003050
Misha Brukman9c003d82004-07-30 12:50:08 +00003051 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00003052 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3053 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3054 I.getName()+".demorgan"), I);
3055 return BinaryOperator::createNot(And);
3056 }
Chris Lattner3e327a42003-03-10 23:13:59 +00003057 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00003058
Chris Lattner3ac7c262003-08-13 20:16:26 +00003059 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003060 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00003061 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3062 return R;
3063
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003064 Value *LHSVal, *RHSVal;
3065 ConstantInt *LHSCst, *RHSCst;
3066 Instruction::BinaryOps LHSCC, RHSCC;
3067 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3068 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3069 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3070 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003071 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003072 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3073 // Ensure that the larger constant is on the RHS.
3074 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3075 SetCondInst *LHS = cast<SetCondInst>(Op0);
3076 if (cast<ConstantBool>(Cmp)->getValue()) {
3077 std::swap(LHS, RHS);
3078 std::swap(LHSCst, RHSCst);
3079 std::swap(LHSCC, RHSCC);
3080 }
3081
3082 // At this point, we know we have have two setcc instructions
3083 // comparing a value against two constants and or'ing the result
3084 // together. Because of the above check, we know that we only have
3085 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3086 // FoldSetCCLogical check above), that the two constants are not
3087 // equal.
3088 assert(LHSCst != RHSCst && "Compares not folded above?");
3089
3090 switch (LHSCC) {
3091 default: assert(0 && "Unknown integer condition code!");
3092 case Instruction::SetEQ:
3093 switch (RHSCC) {
3094 default: assert(0 && "Unknown integer condition code!");
3095 case Instruction::SetEQ:
3096 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3097 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3098 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3099 LHSVal->getName()+".off");
3100 InsertNewInstBefore(Add, I);
3101 const Type *UnsType = Add->getType()->getUnsignedVersion();
3102 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3103 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3104 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3105 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3106 }
3107 break; // (X == 13 | X == 15) -> no change
3108
Chris Lattner5c219462005-04-19 06:04:18 +00003109 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3110 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003111 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3112 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3113 return ReplaceInstUsesWith(I, RHS);
3114 }
3115 break;
3116 case Instruction::SetNE:
3117 switch (RHSCC) {
3118 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003119 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3120 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3121 return ReplaceInstUsesWith(I, LHS);
3122 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00003123 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003124 return ReplaceInstUsesWith(I, ConstantBool::True);
3125 }
3126 break;
3127 case Instruction::SetLT:
3128 switch (RHSCC) {
3129 default: assert(0 && "Unknown integer condition code!");
3130 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3131 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00003132 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3133 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00003134 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3135 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3136 return ReplaceInstUsesWith(I, RHS);
3137 }
3138 break;
3139 case Instruction::SetGT:
3140 switch (RHSCC) {
3141 default: assert(0 && "Unknown integer condition code!");
3142 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3143 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3144 return ReplaceInstUsesWith(I, LHS);
3145 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3146 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3147 return ReplaceInstUsesWith(I, ConstantBool::True);
3148 }
3149 }
3150 }
3151 }
Chris Lattner3af10532006-05-05 06:39:07 +00003152
3153 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3154 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003155 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003156 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003157 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003158 // Only do this if the casts both really cause code to be generated.
3159 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3160 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003161 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3162 Op1C->getOperand(0),
3163 I.getName());
3164 InsertNewInstBefore(NewOp, I);
3165 return new CastInst(NewOp, I.getType());
3166 }
3167 }
3168
Chris Lattner15212982005-09-18 03:42:07 +00003169
Chris Lattner113f4f42002-06-25 16:13:24 +00003170 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003171}
3172
Chris Lattnerc2076352004-02-16 01:20:27 +00003173// XorSelf - Implements: X ^ X --> 0
3174struct XorSelf {
3175 Value *RHS;
3176 XorSelf(Value *rhs) : RHS(rhs) {}
3177 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3178 Instruction *apply(BinaryOperator &Xor) const {
3179 return &Xor;
3180 }
3181};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003182
3183
Chris Lattner113f4f42002-06-25 16:13:24 +00003184Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003185 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003186 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003187
Chris Lattner81a7a232004-10-16 18:11:37 +00003188 if (isa<UndefValue>(Op1))
3189 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3190
Chris Lattnerc2076352004-02-16 01:20:27 +00003191 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3192 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3193 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00003194 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00003195 }
Chris Lattner5b2edb12006-02-12 08:02:11 +00003196
3197 // See if we can simplify any instructions used by the instruction whose sole
3198 // purpose is to compute bits we don't care about.
3199 uint64_t KnownZero, KnownOne;
Chris Lattnerd70d9f52006-03-25 21:58:26 +00003200 if (!isa<PackedType>(I.getType()) &&
3201 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner5b2edb12006-02-12 08:02:11 +00003202 KnownZero, KnownOne))
3203 return &I;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003204
Chris Lattner97638592003-07-23 21:37:07 +00003205 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner97638592003-07-23 21:37:07 +00003206 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003207 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00003208 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003209 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003210 return new SetCondInst(SCI->getInverseCondition(),
3211 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00003212
Chris Lattner8f2f5982003-11-05 01:06:05 +00003213 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003214 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3215 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003216 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3217 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003218 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003219 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003220 }
Chris Lattner023a4832004-06-18 06:07:51 +00003221
3222 // ~(~X & Y) --> (X | ~Y)
3223 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3224 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3225 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3226 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00003227 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00003228 Op0I->getOperand(1)->getName()+".not");
3229 InsertNewInstBefore(NotY, I);
3230 return BinaryOperator::createOr(Op0NotVal, NotY);
3231 }
3232 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003233
Chris Lattner97638592003-07-23 21:37:07 +00003234 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner5b2edb12006-02-12 08:02:11 +00003235 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner0f68fa62003-11-04 23:37:10 +00003236 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003237 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003238 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3239 return BinaryOperator::createSub(
3240 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003241 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00003242 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003243 }
Chris Lattnerf78df7c2006-02-26 19:57:54 +00003244 } else if (Op0I->getOpcode() == Instruction::Or) {
3245 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3246 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3247 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3248 // Anything in both C1 and C2 is known to be zero, remove it from
3249 // NewRHS.
3250 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3251 NewRHS = ConstantExpr::getAnd(NewRHS,
3252 ConstantExpr::getNot(CommonBits));
3253 WorkList.push_back(Op0I);
3254 I.setOperand(0, Op0I->getOperand(0));
3255 I.setOperand(1, NewRHS);
3256 return &I;
3257 }
Chris Lattner97638592003-07-23 21:37:07 +00003258 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00003259 }
Chris Lattner183b3362004-04-09 19:05:30 +00003260
3261 // Try to fold constant and into select arguments.
3262 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003263 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003264 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003265 if (isa<PHINode>(Op0))
3266 if (Instruction *NV = FoldOpIntoPhi(I))
3267 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003268 }
3269
Chris Lattnerbb74e222003-03-10 23:06:50 +00003270 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003271 if (X == Op1)
3272 return ReplaceInstUsesWith(I,
3273 ConstantIntegral::getAllOnesValue(I.getType()));
3274
Chris Lattnerbb74e222003-03-10 23:06:50 +00003275 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00003276 if (X == Op0)
3277 return ReplaceInstUsesWith(I,
3278 ConstantIntegral::getAllOnesValue(I.getType()));
3279
Chris Lattnerdcd07922006-04-01 08:03:55 +00003280 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00003281 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003282 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003283 Op1I->swapOperands();
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003284 I.swapOperands();
3285 std::swap(Op0, Op1);
3286 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003287 I.swapOperands(); // Simplified below.
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003288 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003289 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003290 } else if (Op1I->getOpcode() == Instruction::Xor) {
3291 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3292 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3293 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3294 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003295 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3296 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3297 Op1I->swapOperands();
3298 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3299 I.swapOperands(); // Simplified below.
3300 std::swap(Op0, Op1);
3301 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003302 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003303
Chris Lattnerdcd07922006-04-01 08:03:55 +00003304 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003305 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003306 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003307 Op0I->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003308 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerdcd07922006-04-01 08:03:55 +00003309 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3310 InsertNewInstBefore(NotB, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003311 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003312 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00003313 } else if (Op0I->getOpcode() == Instruction::Xor) {
3314 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3315 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3316 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3317 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnerdcd07922006-04-01 08:03:55 +00003318 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3319 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3320 Op0I->swapOperands();
Chris Lattner6cf49142006-04-01 22:05:01 +00003321 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3322 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattnerdcd07922006-04-01 08:03:55 +00003323 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3324 InsertNewInstBefore(N, I);
3325 return BinaryOperator::createAnd(N, Op1);
3326 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00003327 }
3328
Chris Lattner3ac7c262003-08-13 20:16:26 +00003329 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3330 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3331 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3332 return R;
3333
Chris Lattner3af10532006-05-05 06:39:07 +00003334 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3335 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattnere745c7d2006-05-05 20:51:30 +00003336 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner3af10532006-05-05 06:39:07 +00003337 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattnere745c7d2006-05-05 20:51:30 +00003338 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner1d441ad2006-05-06 09:00:16 +00003339 // Only do this if the casts both really cause code to be generated.
3340 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3341 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner3af10532006-05-05 06:39:07 +00003342 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3343 Op1C->getOperand(0),
3344 I.getName());
3345 InsertNewInstBefore(NewOp, I);
3346 return new CastInst(NewOp, I.getType());
3347 }
3348 }
3349
Chris Lattner113f4f42002-06-25 16:13:24 +00003350 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003351}
3352
Chris Lattner6862fbd2004-09-29 17:40:11 +00003353/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3354/// overflowed for this type.
3355static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3356 ConstantInt *In2) {
3357 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3358 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3359}
3360
3361static bool isPositive(ConstantInt *C) {
3362 return cast<ConstantSInt>(C)->getValue() >= 0;
3363}
3364
3365/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3366/// overflowed for this type.
3367static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3368 ConstantInt *In2) {
3369 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3370
3371 if (In1->getType()->isUnsigned())
3372 return cast<ConstantUInt>(Result)->getValue() <
3373 cast<ConstantUInt>(In1)->getValue();
3374 if (isPositive(In1) != isPositive(In2))
3375 return false;
3376 if (isPositive(In1))
3377 return cast<ConstantSInt>(Result)->getValue() <
3378 cast<ConstantSInt>(In1)->getValue();
3379 return cast<ConstantSInt>(Result)->getValue() >
3380 cast<ConstantSInt>(In1)->getValue();
3381}
3382
Chris Lattner0798af32005-01-13 20:14:25 +00003383/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3384/// code necessary to compute the offset from the base pointer (without adding
3385/// in the base pointer). Return the result as a signed integer of intptr size.
3386static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3387 TargetData &TD = IC.getTargetData();
3388 gep_type_iterator GTI = gep_type_begin(GEP);
3389 const Type *UIntPtrTy = TD.getIntPtrType();
3390 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3391 Value *Result = Constant::getNullValue(SIntPtrTy);
3392
3393 // Build a mask for high order bits.
Chris Lattner77defba2006-02-07 07:00:41 +00003394 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner0798af32005-01-13 20:14:25 +00003395
Chris Lattner0798af32005-01-13 20:14:25 +00003396 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3397 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00003398 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00003399 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3400 SIntPtrTy);
3401 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3402 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003403 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00003404 Scale = ConstantExpr::getMul(OpC, Scale);
3405 if (Constant *RC = dyn_cast<Constant>(Result))
3406 Result = ConstantExpr::getAdd(RC, Scale);
3407 else {
3408 // Emit an add instruction.
3409 Result = IC.InsertNewInstBefore(
3410 BinaryOperator::createAdd(Result, Scale,
3411 GEP->getName()+".offs"), I);
3412 }
3413 }
3414 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00003415 // Convert to correct type.
3416 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3417 Op->getName()+".c"), I);
3418 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003419 // We'll let instcombine(mul) convert this to a shl if possible.
3420 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3421 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00003422
3423 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00003424 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00003425 GEP->getName()+".offs"), I);
3426 }
3427 }
3428 return Result;
3429}
3430
3431/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3432/// else. At this point we know that the GEP is on the LHS of the comparison.
3433Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3434 Instruction::BinaryOps Cond,
3435 Instruction &I) {
3436 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00003437
3438 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3439 if (isa<PointerType>(CI->getOperand(0)->getType()))
3440 RHS = CI->getOperand(0);
3441
Chris Lattner0798af32005-01-13 20:14:25 +00003442 Value *PtrBase = GEPLHS->getOperand(0);
3443 if (PtrBase == RHS) {
3444 // As an optimization, we don't actually have to compute the actual value of
3445 // OFFSET if this is a seteq or setne comparison, just return whether each
3446 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00003447 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3448 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003449 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3450 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00003451 bool EmitIt = true;
3452 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3453 if (isa<UndefValue>(C)) // undef index -> undef.
3454 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3455 if (C->isNullValue())
3456 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00003457 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3458 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00003459 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00003460 return ReplaceInstUsesWith(I, // No comparison is needed here.
3461 ConstantBool::get(Cond == Instruction::SetNE));
3462 }
3463
3464 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003465 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00003466 new SetCondInst(Cond, GEPLHS->getOperand(i),
3467 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3468 if (InVal == 0)
3469 InVal = Comp;
3470 else {
3471 InVal = InsertNewInstBefore(InVal, I);
3472 InsertNewInstBefore(Comp, I);
3473 if (Cond == Instruction::SetNE) // True if any are unequal
3474 InVal = BinaryOperator::createOr(InVal, Comp);
3475 else // True if all are equal
3476 InVal = BinaryOperator::createAnd(InVal, Comp);
3477 }
3478 }
3479 }
3480
3481 if (InVal)
3482 return InVal;
3483 else
3484 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3485 ConstantBool::get(Cond == Instruction::SetEQ));
3486 }
Chris Lattner0798af32005-01-13 20:14:25 +00003487
3488 // Only lower this if the setcc is the only user of the GEP or if we expect
3489 // the result to fold to a constant!
3490 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3491 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3492 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3493 return new SetCondInst(Cond, Offset,
3494 Constant::getNullValue(Offset->getType()));
3495 }
3496 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003497 // If the base pointers are different, but the indices are the same, just
3498 // compare the base pointer.
3499 if (PtrBase != GEPRHS->getOperand(0)) {
3500 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003501 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00003502 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003503 if (IndicesTheSame)
3504 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3505 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3506 IndicesTheSame = false;
3507 break;
3508 }
3509
3510 // If all indices are the same, just compare the base pointers.
3511 if (IndicesTheSame)
3512 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3513 GEPRHS->getOperand(0));
3514
3515 // Otherwise, the base pointers are different and the indices are
3516 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00003517 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00003518 }
Chris Lattner0798af32005-01-13 20:14:25 +00003519
Chris Lattner81e84172005-01-13 22:25:21 +00003520 // If one of the GEPs has all zero indices, recurse.
3521 bool AllZeros = true;
3522 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3523 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3524 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3525 AllZeros = false;
3526 break;
3527 }
3528 if (AllZeros)
3529 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3530 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00003531
3532 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00003533 AllZeros = true;
3534 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3535 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3536 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3537 AllZeros = false;
3538 break;
3539 }
3540 if (AllZeros)
3541 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3542
Chris Lattner4fa89822005-01-14 00:20:05 +00003543 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3544 // If the GEPs only differ by one index, compare it.
3545 unsigned NumDifferences = 0; // Keep track of # differences.
3546 unsigned DiffOperand = 0; // The operand that differs.
3547 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3548 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003549 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3550 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003551 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00003552 NumDifferences = 2;
3553 break;
3554 } else {
3555 if (NumDifferences++) break;
3556 DiffOperand = i;
3557 }
3558 }
3559
3560 if (NumDifferences == 0) // SAME GEP?
3561 return ReplaceInstUsesWith(I, // No comparison is needed here.
3562 ConstantBool::get(Cond == Instruction::SetEQ));
3563 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00003564 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3565 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00003566
3567 // Convert the operands to signed values to make sure to perform a
3568 // signed comparison.
3569 const Type *NewTy = LHSV->getType()->getSignedVersion();
3570 if (LHSV->getType() != NewTy)
3571 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3572 LHSV->getName()), I);
3573 if (RHSV->getType() != NewTy)
3574 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3575 RHSV->getName()), I);
3576 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00003577 }
3578 }
3579
Chris Lattner0798af32005-01-13 20:14:25 +00003580 // Only lower this if the setcc is the only user of the GEP or if we expect
3581 // the result to fold to a constant!
3582 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3583 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3584 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3585 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3586 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3587 return new SetCondInst(Cond, L, R);
3588 }
3589 }
3590 return 0;
3591}
3592
3593
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003594Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00003595 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003596 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3597 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003598
3599 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003600 if (Op0 == Op1)
3601 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00003602
Chris Lattner81a7a232004-10-16 18:11:37 +00003603 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3604 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3605
Chris Lattner15ff1e12004-11-14 07:33:16 +00003606 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3607 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003608 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3609 isa<ConstantPointerNull>(Op0)) &&
3610 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00003611 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003612 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3613
3614 // setcc's with boolean values can always be turned into bitwise operations
3615 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00003616 switch (I.getOpcode()) {
3617 default: assert(0 && "Invalid setcc instruction!");
3618 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003619 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003620 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00003621 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003622 }
Chris Lattner4456da62004-08-11 00:50:51 +00003623 case Instruction::SetNE:
3624 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003625
Chris Lattner4456da62004-08-11 00:50:51 +00003626 case Instruction::SetGT:
3627 std::swap(Op0, Op1); // Change setgt -> setlt
3628 // FALL THROUGH
3629 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3630 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3631 InsertNewInstBefore(Not, I);
3632 return BinaryOperator::createAnd(Not, Op1);
3633 }
3634 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003635 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00003636 // FALL THROUGH
3637 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3638 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3639 InsertNewInstBefore(Not, I);
3640 return BinaryOperator::createOr(Not, Op1);
3641 }
3642 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003643 }
3644
Chris Lattner2dd01742004-06-09 04:24:29 +00003645 // See if we are doing a comparison between a constant and an instruction that
3646 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00003647 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00003648 // Check to see if we are comparing against the minimum or maximum value...
3649 if (CI->isMinValue()) {
3650 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3651 return ReplaceInstUsesWith(I, ConstantBool::False);
3652 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3653 return ReplaceInstUsesWith(I, ConstantBool::True);
3654 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3655 return BinaryOperator::createSetEQ(Op0, Op1);
3656 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3657 return BinaryOperator::createSetNE(Op0, Op1);
3658
3659 } else if (CI->isMaxValue()) {
3660 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3661 return ReplaceInstUsesWith(I, ConstantBool::False);
3662 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3663 return ReplaceInstUsesWith(I, ConstantBool::True);
3664 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3665 return BinaryOperator::createSetEQ(Op0, Op1);
3666 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3667 return BinaryOperator::createSetNE(Op0, Op1);
3668
3669 // Comparing against a value really close to min or max?
3670 } else if (isMinValuePlusOne(CI)) {
3671 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3672 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3673 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3674 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3675
3676 } else if (isMaxValueMinusOne(CI)) {
3677 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3678 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3679 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3680 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3681 }
3682
3683 // If we still have a setle or setge instruction, turn it into the
3684 // appropriate setlt or setgt instruction. Since the border cases have
3685 // already been handled above, this requires little checking.
3686 //
3687 if (I.getOpcode() == Instruction::SetLE)
3688 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3689 if (I.getOpcode() == Instruction::SetGE)
3690 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3691
Chris Lattneree0f2802006-02-12 02:07:56 +00003692
3693 // See if we can fold the comparison based on bits known to be zero or one
3694 // in the input.
3695 uint64_t KnownZero, KnownOne;
3696 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3697 KnownZero, KnownOne, 0))
3698 return &I;
3699
3700 // Given the known and unknown bits, compute a range that the LHS could be
3701 // in.
3702 if (KnownOne | KnownZero) {
3703 if (Ty->isUnsigned()) { // Unsigned comparison.
3704 uint64_t Min, Max;
3705 uint64_t RHSVal = CI->getZExtValue();
3706 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3707 Min, Max);
3708 switch (I.getOpcode()) { // LE/GE have been folded already.
3709 default: assert(0 && "Unknown setcc opcode!");
3710 case Instruction::SetEQ:
3711 if (Max < RHSVal || Min > RHSVal)
3712 return ReplaceInstUsesWith(I, ConstantBool::False);
3713 break;
3714 case Instruction::SetNE:
3715 if (Max < RHSVal || Min > RHSVal)
3716 return ReplaceInstUsesWith(I, ConstantBool::True);
3717 break;
3718 case Instruction::SetLT:
3719 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3720 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3721 break;
3722 case Instruction::SetGT:
3723 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3724 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3725 break;
3726 }
3727 } else { // Signed comparison.
3728 int64_t Min, Max;
3729 int64_t RHSVal = CI->getSExtValue();
3730 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3731 Min, Max);
3732 switch (I.getOpcode()) { // LE/GE have been folded already.
3733 default: assert(0 && "Unknown setcc opcode!");
3734 case Instruction::SetEQ:
3735 if (Max < RHSVal || Min > RHSVal)
3736 return ReplaceInstUsesWith(I, ConstantBool::False);
3737 break;
3738 case Instruction::SetNE:
3739 if (Max < RHSVal || Min > RHSVal)
3740 return ReplaceInstUsesWith(I, ConstantBool::True);
3741 break;
3742 case Instruction::SetLT:
3743 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3744 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3745 break;
3746 case Instruction::SetGT:
3747 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3748 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3749 break;
3750 }
3751 }
3752 }
3753
3754
Chris Lattnere1e10e12004-05-25 06:32:08 +00003755 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003756 switch (LHSI->getOpcode()) {
3757 case Instruction::And:
3758 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3759 LHSI->getOperand(0)->hasOneUse()) {
3760 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3761 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3762 // happens a LOT in code produced by the C front-end, for bitfield
3763 // access.
3764 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattneree0f2802006-02-12 02:07:56 +00003765 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3766
3767 // Check to see if there is a noop-cast between the shift and the and.
3768 if (!Shift) {
3769 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3770 if (CI->getOperand(0)->getType()->isIntegral() &&
3771 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3772 CI->getType()->getPrimitiveSizeInBits())
3773 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3774 }
3775
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003776 ConstantUInt *ShAmt;
3777 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattneree0f2802006-02-12 02:07:56 +00003778 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3779 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003780
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003781 // We can fold this as long as we can't shift unknown bits
3782 // into the mask. This can only happen with signed shift
3783 // rights, as they sign-extend.
3784 if (ShAmt) {
3785 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattneree0f2802006-02-12 02:07:56 +00003786 Ty->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003787 if (!CanFold) {
3788 // To test for the bad case of the signed shr, see if any
3789 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00003790 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3791 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3792
3793 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003794 Constant *ShVal =
Chris Lattneree0f2802006-02-12 02:07:56 +00003795 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3796 OShAmt);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003797 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3798 CanFold = true;
3799 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003800
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003801 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00003802 Constant *NewCst;
3803 if (Shift->getOpcode() == Instruction::Shl)
3804 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3805 else
3806 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003807
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003808 // Check to see if we are shifting out any of the bits being
3809 // compared.
3810 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3811 // If we shifted bits out, the fold is not going to work out.
3812 // As a special case, check to see if this means that the
3813 // result is always true or false now.
3814 if (I.getOpcode() == Instruction::SetEQ)
3815 return ReplaceInstUsesWith(I, ConstantBool::False);
3816 if (I.getOpcode() == Instruction::SetNE)
3817 return ReplaceInstUsesWith(I, ConstantBool::True);
3818 } else {
3819 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00003820 Constant *NewAndCST;
3821 if (Shift->getOpcode() == Instruction::Shl)
3822 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3823 else
3824 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3825 LHSI->setOperand(1, NewAndCST);
Chris Lattneree0f2802006-02-12 02:07:56 +00003826 if (AndTy == Ty)
3827 LHSI->setOperand(0, Shift->getOperand(0));
3828 else {
3829 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3830 *Shift);
3831 LHSI->setOperand(0, NewCast);
3832 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003833 WorkList.push_back(Shift); // Shift is dead.
3834 AddUsesToWorkList(I);
3835 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00003836 }
3837 }
Chris Lattner35167c32004-06-09 07:59:58 +00003838 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00003839 }
3840 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003841
Chris Lattner272d5ca2004-09-28 18:22:15 +00003842 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3843 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3844 switch (I.getOpcode()) {
3845 default: break;
3846 case Instruction::SetEQ:
3847 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003848 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3849
3850 // Check that the shift amount is in range. If not, don't perform
3851 // undefined shifts. When the shift is visited it will be
3852 // simplified.
3853 if (ShAmt->getValue() >= TypeBits)
3854 break;
3855
Chris Lattner272d5ca2004-09-28 18:22:15 +00003856 // If we are comparing against bits always shifted out, the
3857 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003858 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00003859 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3860 if (Comp != CI) {// Comparing against a bit that we know is zero.
3861 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3862 Constant *Cst = ConstantBool::get(IsSetNE);
3863 return ReplaceInstUsesWith(I, Cst);
3864 }
3865
3866 if (LHSI->hasOneUse()) {
3867 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003868 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003869 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3870
3871 Constant *Mask;
3872 if (CI->getType()->isUnsigned()) {
3873 Mask = ConstantUInt::get(CI->getType(), Val);
3874 } else if (ShAmtVal != 0) {
3875 Mask = ConstantSInt::get(CI->getType(), Val);
3876 } else {
3877 Mask = ConstantInt::getAllOnesValue(CI->getType());
3878 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003879
Chris Lattner272d5ca2004-09-28 18:22:15 +00003880 Instruction *AndI =
3881 BinaryOperator::createAnd(LHSI->getOperand(0),
3882 Mask, LHSI->getName()+".mask");
3883 Value *And = InsertNewInstBefore(AndI, I);
3884 return new SetCondInst(I.getOpcode(), And,
3885 ConstantExpr::getUShr(CI, ShAmt));
3886 }
3887 }
3888 }
3889 }
3890 break;
3891
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003892 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00003893 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00003894 switch (I.getOpcode()) {
3895 default: break;
3896 case Instruction::SetEQ:
3897 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00003898
3899 // Check that the shift amount is in range. If not, don't perform
3900 // undefined shifts. When the shift is visited it will be
3901 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00003902 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00003903 if (ShAmt->getValue() >= TypeBits)
3904 break;
3905
Chris Lattner1023b872004-09-27 16:18:50 +00003906 // If we are comparing against bits always shifted out, the
3907 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003908 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00003909 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003910
Chris Lattner1023b872004-09-27 16:18:50 +00003911 if (Comp != CI) {// Comparing against a bit that we know is zero.
3912 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3913 Constant *Cst = ConstantBool::get(IsSetNE);
3914 return ReplaceInstUsesWith(I, Cst);
3915 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003916
Chris Lattner1023b872004-09-27 16:18:50 +00003917 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003918 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00003919
Chris Lattner1023b872004-09-27 16:18:50 +00003920 // Otherwise strength reduce the shift into an and.
3921 uint64_t Val = ~0ULL; // All ones.
3922 Val <<= ShAmtVal; // Shift over to the right spot.
3923
3924 Constant *Mask;
3925 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00003926 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00003927 Mask = ConstantUInt::get(CI->getType(), Val);
3928 } else {
3929 Mask = ConstantSInt::get(CI->getType(), Val);
3930 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003931
Chris Lattner1023b872004-09-27 16:18:50 +00003932 Instruction *AndI =
3933 BinaryOperator::createAnd(LHSI->getOperand(0),
3934 Mask, LHSI->getName()+".mask");
3935 Value *And = InsertNewInstBefore(AndI, I);
3936 return new SetCondInst(I.getOpcode(), And,
3937 ConstantExpr::getShl(CI, ShAmt));
3938 }
3939 break;
3940 }
3941 }
3942 }
3943 break;
Chris Lattner7e794272004-09-24 15:21:34 +00003944
Chris Lattner6862fbd2004-09-29 17:40:11 +00003945 case Instruction::Div:
3946 // Fold: (div X, C1) op C2 -> range check
3947 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3948 // Fold this div into the comparison, producing a range check.
3949 // Determine, based on the divide type, what the range is being
3950 // checked. If there is an overflow on the low or high side, remember
3951 // it, otherwise compute the range [low, hi) bounding the new value.
3952 bool LoOverflow = false, HiOverflow = 0;
3953 ConstantInt *LoBound = 0, *HiBound = 0;
3954
3955 ConstantInt *Prod;
3956 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3957
Chris Lattnera92af962004-10-11 19:40:04 +00003958 Instruction::BinaryOps Opcode = I.getOpcode();
3959
Chris Lattner6862fbd2004-09-29 17:40:11 +00003960 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3961 } else if (LHSI->getType()->isUnsigned()) { // udiv
3962 LoBound = Prod;
3963 LoOverflow = ProdOV;
3964 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3965 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3966 if (CI->isNullValue()) { // (X / pos) op 0
3967 // Can't overflow.
3968 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3969 HiBound = DivRHS;
3970 } else if (isPositive(CI)) { // (X / pos) op pos
3971 LoBound = Prod;
3972 LoOverflow = ProdOV;
3973 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3974 } else { // (X / pos) op neg
3975 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3976 LoOverflow = AddWithOverflow(LoBound, Prod,
3977 cast<ConstantInt>(DivRHSH));
3978 HiBound = Prod;
3979 HiOverflow = ProdOV;
3980 }
3981 } else { // Divisor is < 0.
3982 if (CI->isNullValue()) { // (X / neg) op 0
3983 LoBound = AddOne(DivRHS);
3984 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00003985 if (HiBound == DivRHS)
3986 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00003987 } else if (isPositive(CI)) { // (X / neg) op pos
3988 HiOverflow = LoOverflow = ProdOV;
3989 if (!LoOverflow)
3990 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3991 HiBound = AddOne(Prod);
3992 } else { // (X / neg) op neg
3993 LoBound = Prod;
3994 LoOverflow = HiOverflow = ProdOV;
3995 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3996 }
Chris Lattner0b41e862004-10-08 19:15:44 +00003997
Chris Lattnera92af962004-10-11 19:40:04 +00003998 // Dividing by a negate swaps the condition.
3999 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00004000 }
4001
4002 if (LoBound) {
4003 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00004004 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00004005 default: assert(0 && "Unhandled setcc opcode!");
4006 case Instruction::SetEQ:
4007 if (LoOverflow && HiOverflow)
4008 return ReplaceInstUsesWith(I, ConstantBool::False);
4009 else if (HiOverflow)
4010 return new SetCondInst(Instruction::SetGE, X, LoBound);
4011 else if (LoOverflow)
4012 return new SetCondInst(Instruction::SetLT, X, HiBound);
4013 else
4014 return InsertRangeTest(X, LoBound, HiBound, true, I);
4015 case Instruction::SetNE:
4016 if (LoOverflow && HiOverflow)
4017 return ReplaceInstUsesWith(I, ConstantBool::True);
4018 else if (HiOverflow)
4019 return new SetCondInst(Instruction::SetLT, X, LoBound);
4020 else if (LoOverflow)
4021 return new SetCondInst(Instruction::SetGE, X, HiBound);
4022 else
4023 return InsertRangeTest(X, LoBound, HiBound, false, I);
4024 case Instruction::SetLT:
4025 if (LoOverflow)
4026 return ReplaceInstUsesWith(I, ConstantBool::False);
4027 return new SetCondInst(Instruction::SetLT, X, LoBound);
4028 case Instruction::SetGT:
4029 if (HiOverflow)
4030 return ReplaceInstUsesWith(I, ConstantBool::False);
4031 return new SetCondInst(Instruction::SetGE, X, HiBound);
4032 }
4033 }
4034 }
4035 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00004036 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004037
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004038 // Simplify seteq and setne instructions...
4039 if (I.getOpcode() == Instruction::SetEQ ||
4040 I.getOpcode() == Instruction::SetNE) {
4041 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4042
Chris Lattnercfbce7c2003-07-23 17:26:36 +00004043 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004044 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00004045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4046 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00004047 case Instruction::Rem:
4048 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4049 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4050 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00004051 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4052 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4053 if (isPowerOf2_64(V)) {
4054 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00004055 const Type *UTy = BO->getType()->getUnsignedVersion();
4056 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4057 UTy, "tmp"), I);
4058 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4059 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4060 RHSCst, BO->getName()), I);
4061 return BinaryOperator::create(I.getOpcode(), NewRem,
4062 Constant::getNullValue(UTy));
4063 }
Chris Lattner22d00a82005-08-02 19:16:58 +00004064 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004065 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00004066
Chris Lattnerc992add2003-08-13 05:33:12 +00004067 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00004068 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4069 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00004070 if (BO->hasOneUse())
4071 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4072 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00004073 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004074 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4075 // efficiently invertible, or if the add has just this one use.
4076 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004077
Chris Lattnerc992add2003-08-13 05:33:12 +00004078 if (Value *NegVal = dyn_castNegVal(BOp1))
4079 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4080 else if (Value *NegVal = dyn_castNegVal(BOp0))
4081 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004082 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00004083 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4084 BO->setName("");
4085 InsertNewInstBefore(Neg, I);
4086 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4087 }
4088 }
4089 break;
4090 case Instruction::Xor:
4091 // For the xor case, we can xor two constants together, eliminating
4092 // the explicit xor.
4093 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4094 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004095 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00004096
4097 // FALLTHROUGH
4098 case Instruction::Sub:
4099 // Replace (([sub|xor] A, B) != 0) with (A != B)
4100 if (CI->isNullValue())
4101 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4102 BO->getOperand(1));
4103 break;
4104
4105 case Instruction::Or:
4106 // If bits are being or'd in that are not present in the constant we
4107 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004108 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004109 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004110 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004111 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00004112 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004113 break;
4114
4115 case Instruction::And:
4116 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004117 // If bits are being compared against that are and'd out, then the
4118 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00004119 if (!ConstantExpr::getAnd(CI,
4120 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004121 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00004122
Chris Lattner35167c32004-06-09 07:59:58 +00004123 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00004124 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00004125 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4126 Instruction::SetNE, Op0,
4127 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00004128
Chris Lattnerc992add2003-08-13 05:33:12 +00004129 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4130 // to be a signed value as appropriate.
4131 if (isSignBit(BOC)) {
4132 Value *X = BO->getOperand(0);
4133 // If 'X' is not signed, insert a cast now...
4134 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00004135 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004136 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00004137 }
4138 return new SetCondInst(isSetNE ? Instruction::SetLT :
4139 Instruction::SetGE, X,
4140 Constant::getNullValue(X->getType()));
4141 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004142
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004143 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00004144 if (CI->isNullValue() && isHighOnes(BOC)) {
4145 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004146 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004147
4148 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004149 if (NegX->getType()->isSigned()) {
4150 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4151 X = InsertCastBefore(X, DestTy, I);
4152 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004153 }
4154
4155 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00004156 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00004157 }
4158
Chris Lattnerd492a0b2003-07-23 17:02:11 +00004159 }
Chris Lattnerc992add2003-08-13 05:33:12 +00004160 default: break;
4161 }
4162 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00004163 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00004164 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00004165 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4166 Value *CastOp = Cast->getOperand(0);
4167 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004168 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00004169 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004170 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004171 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00004172 "Source and destination signednesses should differ!");
4173 if (Cast->getType()->isSigned()) {
4174 // If this is a signed comparison, check for comparisons in the
4175 // vicinity of zero.
4176 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4177 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004178 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004179 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004180 else if (I.getOpcode() == Instruction::SetGT &&
4181 cast<ConstantSInt>(CI)->getValue() == -1)
4182 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004183 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004184 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004185 } else {
4186 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4187 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004188 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00004189 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004190 return BinaryOperator::createSetGT(CastOp,
4191 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004192 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004193 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00004194 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004195 return BinaryOperator::createSetLT(CastOp,
4196 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00004197 }
4198 }
4199 }
Chris Lattnere967b342003-06-04 05:10:11 +00004200 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004201 }
4202
Chris Lattner77c32c32005-04-23 15:31:55 +00004203 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4204 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4205 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4206 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00004207 case Instruction::GetElementPtr:
4208 if (RHSC->isNullValue()) {
4209 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4210 bool isAllZeros = true;
4211 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4212 if (!isa<Constant>(LHSI->getOperand(i)) ||
4213 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4214 isAllZeros = false;
4215 break;
4216 }
4217 if (isAllZeros)
4218 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4219 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4220 }
4221 break;
4222
Chris Lattner77c32c32005-04-23 15:31:55 +00004223 case Instruction::PHI:
4224 if (Instruction *NV = FoldOpIntoPhi(I))
4225 return NV;
4226 break;
4227 case Instruction::Select:
4228 // If either operand of the select is a constant, we can fold the
4229 // comparison into the select arms, which will cause one to be
4230 // constant folded and the select turned into a bitwise or.
4231 Value *Op1 = 0, *Op2 = 0;
4232 if (LHSI->hasOneUse()) {
4233 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4234 // Fold the known value into the constant operand.
4235 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4236 // Insert a new SetCC of the other select operand.
4237 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4238 LHSI->getOperand(2), RHSC,
4239 I.getName()), I);
4240 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4241 // Fold the known value into the constant operand.
4242 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4243 // Insert a new SetCC of the other select operand.
4244 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4245 LHSI->getOperand(1), RHSC,
4246 I.getName()), I);
4247 }
4248 }
Jeff Cohen82639852005-04-23 21:38:35 +00004249
Chris Lattner77c32c32005-04-23 15:31:55 +00004250 if (Op1)
4251 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4252 break;
4253 }
4254 }
4255
Chris Lattner0798af32005-01-13 20:14:25 +00004256 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4257 if (User *GEP = dyn_castGetElementPtr(Op0))
4258 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4259 return NI;
4260 if (User *GEP = dyn_castGetElementPtr(Op1))
4261 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4262 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4263 return NI;
4264
Chris Lattner16930792003-11-03 04:25:02 +00004265 // Test to see if the operands of the setcc are casted versions of other
4266 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00004267 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4268 Value *CastOp0 = CI->getOperand(0);
4269 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00004270 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00004271 (I.getOpcode() == Instruction::SetEQ ||
4272 I.getOpcode() == Instruction::SetNE)) {
4273 // We keep moving the cast from the left operand over to the right
4274 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00004275 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004276
Chris Lattner16930792003-11-03 04:25:02 +00004277 // If operand #1 is a cast instruction, see if we can eliminate it as
4278 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00004279 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4280 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00004281 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00004282 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004283
Chris Lattner16930792003-11-03 04:25:02 +00004284 // If Op1 is a constant, we can fold the cast into the constant.
4285 if (Op1->getType() != Op0->getType())
4286 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4287 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4288 } else {
4289 // Otherwise, cast the RHS right before the setcc
4290 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4291 InsertNewInstBefore(cast<Instruction>(Op1), I);
4292 }
4293 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4294 }
4295
Chris Lattner6444c372003-11-03 05:17:03 +00004296 // Handle the special case of: setcc (cast bool to X), <cst>
4297 // This comes up when you have code like
4298 // int X = A < B;
4299 // if (X) ...
4300 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004301 // with a constant or another cast from the same type.
4302 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4303 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4304 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00004305 }
Chris Lattnerf5c8a0b2006-02-27 01:44:11 +00004306
4307 if (I.getOpcode() == Instruction::SetNE ||
4308 I.getOpcode() == Instruction::SetEQ) {
4309 Value *A, *B;
4310 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4311 (A == Op1 || B == Op1)) {
4312 // (A^B) == A -> B == 0
4313 Value *OtherVal = A == Op1 ? B : A;
4314 return BinaryOperator::create(I.getOpcode(), OtherVal,
4315 Constant::getNullValue(A->getType()));
4316 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4317 (A == Op0 || B == Op0)) {
4318 // A == (A^B) -> B == 0
4319 Value *OtherVal = A == Op0 ? B : A;
4320 return BinaryOperator::create(I.getOpcode(), OtherVal,
4321 Constant::getNullValue(A->getType()));
4322 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4323 // (A-B) == A -> B == 0
4324 return BinaryOperator::create(I.getOpcode(), B,
4325 Constant::getNullValue(B->getType()));
4326 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4327 // A == (A-B) -> B == 0
4328 return BinaryOperator::create(I.getOpcode(), B,
4329 Constant::getNullValue(B->getType()));
4330 }
4331 }
Chris Lattner113f4f42002-06-25 16:13:24 +00004332 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004333}
4334
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004335// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4336// We only handle extending casts so far.
4337//
4338Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4339 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4340 const Type *SrcTy = LHSCIOp->getType();
4341 const Type *DestTy = SCI.getOperand(0)->getType();
4342 Value *RHSCIOp;
4343
4344 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00004345 return 0;
4346
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004347 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4348 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4349 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4350
4351 // Is this a sign or zero extension?
4352 bool isSignSrc = SrcTy->isSigned();
4353 bool isSignDest = DestTy->isSigned();
4354
4355 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4356 // Not an extension from the same type?
4357 RHSCIOp = CI->getOperand(0);
4358 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4359 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4360 // Compute the constant that would happen if we truncated to SrcTy then
4361 // reextended to DestTy.
4362 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4363
4364 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4365 RHSCIOp = Res;
4366 } else {
4367 // If the value cannot be represented in the shorter type, we cannot emit
4368 // a simple comparison.
4369 if (SCI.getOpcode() == Instruction::SetEQ)
4370 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4371 if (SCI.getOpcode() == Instruction::SetNE)
4372 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4373
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004374 // Evaluate the comparison for LT.
4375 Value *Result;
4376 if (DestTy->isSigned()) {
4377 // We're performing a signed comparison.
4378 if (isSignSrc) {
4379 // Signed extend and signed comparison.
4380 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4381 Result = ConstantBool::False;
4382 else
4383 Result = ConstantBool::True; // X < (large) --> true
4384 } else {
4385 // Unsigned extend and signed comparison.
4386 if (cast<ConstantSInt>(CI)->getValue() < 0)
4387 Result = ConstantBool::False;
4388 else
4389 Result = ConstantBool::True;
4390 }
4391 } else {
4392 // We're performing an unsigned comparison.
4393 if (!isSignSrc) {
4394 // Unsigned extend & compare -> always true.
4395 Result = ConstantBool::True;
4396 } else {
4397 // We're performing an unsigned comp with a sign extended value.
4398 // This is true if the input is >= 0. [aka >s -1]
4399 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4400 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4401 NegOne, SCI.getName()), SCI);
4402 }
Reid Spencer279fa252004-11-28 21:31:15 +00004403 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004404
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004405 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004406 if (SCI.getOpcode() == Instruction::SetLT) {
4407 return ReplaceInstUsesWith(SCI, Result);
4408 } else {
4409 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4410 if (Constant *CI = dyn_cast<Constant>(Result))
4411 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4412 else
4413 return BinaryOperator::createNot(Result);
4414 }
Chris Lattner03f06f12005-01-17 03:20:02 +00004415 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004416 } else {
4417 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00004418 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004419
Chris Lattner252a8452005-06-16 03:00:08 +00004420 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004421 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4422}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004423
Chris Lattnere8d6c602003-03-10 19:16:08 +00004424Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00004425 assert(I.getOperand(1)->getType() == Type::UByteTy);
4426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004427 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004428
4429 // shl X, 0 == X and shr X, 0 == X
4430 // shl 0, X == 0 and shr 0, X == 0
4431 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00004432 Op0 == Constant::getNullValue(Op0->getType()))
4433 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004434
Chris Lattner81a7a232004-10-16 18:11:37 +00004435 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4436 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00004437 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00004438 else // undef << X -> 0 AND undef >>u X -> 0
4439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4440 }
4441 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00004442 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00004443 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4444 else
4445 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4446 }
4447
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004448 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4449 if (!isLeftShift)
4450 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4451 if (CSI->isAllOnesValue())
4452 return ReplaceInstUsesWith(I, CSI);
4453
Chris Lattner183b3362004-04-09 19:05:30 +00004454 // Try to fold constant and into select arguments.
4455 if (isa<Constant>(Op0))
4456 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00004457 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00004458 return R;
4459
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004460 // See if we can turn a signed shr into an unsigned shr.
4461 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattnerc3ebf402006-02-07 07:27:52 +00004462 if (MaskedValueIsZero(Op0,
4463 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00004464 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4465 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4466 I.getName()), I);
4467 return new CastInst(V, I.getType());
4468 }
4469 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004470
Chris Lattner14553932006-01-06 07:12:35 +00004471 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4472 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4473 return Res;
4474 return 0;
4475}
4476
4477Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4478 ShiftInst &I) {
4479 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerb3309392006-01-06 07:22:22 +00004480 bool isSignedShift = Op0->getType()->isSigned();
4481 bool isUnsignedShift = !isSignedShift;
Chris Lattner14553932006-01-06 07:12:35 +00004482
Chris Lattnerf5b4ef72006-02-12 08:07:37 +00004483 // See if we can simplify any instructions used by the instruction whose sole
4484 // purpose is to compute bits we don't care about.
4485 uint64_t KnownZero, KnownOne;
4486 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4487 KnownZero, KnownOne))
4488 return &I;
4489
Chris Lattner14553932006-01-06 07:12:35 +00004490 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4491 // of a signed value.
4492 //
4493 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4494 if (Op1->getValue() >= TypeBits) {
Chris Lattnerb3309392006-01-06 07:22:22 +00004495 if (isUnsignedShift || isLeftShift)
Chris Lattner14553932006-01-06 07:12:35 +00004496 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4497 else {
4498 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4499 return &I;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00004500 }
Chris Lattner14553932006-01-06 07:12:35 +00004501 }
4502
4503 // ((X*C1) << C2) == (X * (C1 << C2))
4504 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4505 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4506 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4507 return BinaryOperator::createMul(BO->getOperand(0),
4508 ConstantExpr::getShl(BOOp, Op1));
4509
4510 // Try to fold constant and into select arguments.
4511 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4512 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4513 return R;
4514 if (isa<PHINode>(Op0))
4515 if (Instruction *NV = FoldOpIntoPhi(I))
4516 return NV;
4517
4518 if (Op0->hasOneUse()) {
Chris Lattner14553932006-01-06 07:12:35 +00004519 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4520 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4521 Value *V1, *V2;
4522 ConstantInt *CC;
4523 switch (Op0BO->getOpcode()) {
Chris Lattner27cb9db2005-09-18 05:12:10 +00004524 default: break;
4525 case Instruction::Add:
4526 case Instruction::And:
4527 case Instruction::Or:
4528 case Instruction::Xor:
4529 // These operators commute.
4530 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004531 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4532 match(Op0BO->getOperand(1),
Chris Lattner14553932006-01-06 07:12:35 +00004533 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004534 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004535 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004536 Op0BO->getName());
4537 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004538 Instruction *X =
4539 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4540 Op0BO->getOperand(1)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004541 InsertNewInstBefore(X, I); // (X + (Y << C))
4542 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004543 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004544 return BinaryOperator::createAnd(X, C2);
4545 }
Chris Lattner14553932006-01-06 07:12:35 +00004546
Chris Lattner797dee72005-09-18 06:30:59 +00004547 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4548 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4549 match(Op0BO->getOperand(1),
4550 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004551 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004552 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004553 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004554 Op0BO->getOperand(0), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004555 Op0BO->getName());
4556 InsertNewInstBefore(YS, I); // (Y << C)
4557 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004558 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004559 V1->getName()+".mask");
4560 InsertNewInstBefore(XM, I); // X & (CC << C)
4561
4562 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4563 }
Chris Lattner14553932006-01-06 07:12:35 +00004564
Chris Lattner797dee72005-09-18 06:30:59 +00004565 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00004566 case Instruction::Sub:
4567 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004568 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4569 match(Op0BO->getOperand(0),
Chris Lattner14553932006-01-06 07:12:35 +00004570 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner797dee72005-09-18 06:30:59 +00004571 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004572 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004573 Op0BO->getName());
4574 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004575 Instruction *X =
Chris Lattner1df0e982006-05-31 21:14:00 +00004576 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004577 Op0BO->getOperand(0)->getName());
Chris Lattner797dee72005-09-18 06:30:59 +00004578 InsertNewInstBefore(X, I); // (X + (Y << C))
4579 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner14553932006-01-06 07:12:35 +00004580 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner797dee72005-09-18 06:30:59 +00004581 return BinaryOperator::createAnd(X, C2);
4582 }
Chris Lattner14553932006-01-06 07:12:35 +00004583
Chris Lattner1df0e982006-05-31 21:14:00 +00004584 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner797dee72005-09-18 06:30:59 +00004585 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4586 match(Op0BO->getOperand(0),
4587 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner14553932006-01-06 07:12:35 +00004588 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner24cd2fa2006-02-09 07:41:14 +00004589 cast<BinaryOperator>(Op0BO->getOperand(0))
4590 ->getOperand(0)->hasOneUse()) {
Chris Lattner797dee72005-09-18 06:30:59 +00004591 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner14553932006-01-06 07:12:35 +00004592 Op0BO->getOperand(1), Op1,
Chris Lattner797dee72005-09-18 06:30:59 +00004593 Op0BO->getName());
4594 InsertNewInstBefore(YS, I); // (Y << C)
4595 Instruction *XM =
Chris Lattner14553932006-01-06 07:12:35 +00004596 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner797dee72005-09-18 06:30:59 +00004597 V1->getName()+".mask");
4598 InsertNewInstBefore(XM, I); // X & (CC << C)
4599
Chris Lattner1df0e982006-05-31 21:14:00 +00004600 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner797dee72005-09-18 06:30:59 +00004601 }
Chris Lattner14553932006-01-06 07:12:35 +00004602
Chris Lattner27cb9db2005-09-18 05:12:10 +00004603 break;
Chris Lattner14553932006-01-06 07:12:35 +00004604 }
4605
4606
4607 // If the operand is an bitwise operator with a constant RHS, and the
4608 // shift is the only use, we can pull it out of the shift.
4609 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4610 bool isValid = true; // Valid only for And, Or, Xor
4611 bool highBitSet = false; // Transform if high bit of constant set?
4612
4613 switch (Op0BO->getOpcode()) {
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004614 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00004615 case Instruction::Add:
4616 isValid = isLeftShift;
4617 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004618 case Instruction::Or:
4619 case Instruction::Xor:
4620 highBitSet = false;
4621 break;
4622 case Instruction::And:
4623 highBitSet = true;
4624 break;
Chris Lattner14553932006-01-06 07:12:35 +00004625 }
4626
4627 // If this is a signed shift right, and the high bit is modified
4628 // by the logical operation, do not perform the transformation.
4629 // The highBitSet boolean indicates the value of the high bit of
4630 // the constant which would cause it to be modified for this
4631 // operation.
4632 //
Chris Lattnerb3309392006-01-06 07:22:22 +00004633 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner14553932006-01-06 07:12:35 +00004634 uint64_t Val = Op0C->getRawValue();
4635 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4636 }
4637
4638 if (isValid) {
4639 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4640
4641 Instruction *NewShift =
4642 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4643 Op0BO->getName());
4644 Op0BO->setName("");
4645 InsertNewInstBefore(NewShift, I);
4646
4647 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4648 NewRHS);
4649 }
4650 }
4651 }
4652 }
4653
Chris Lattnereb372a02006-01-06 07:52:12 +00004654 // Find out if this is a shift of a shift by a constant.
4655 ShiftInst *ShiftOp = 0;
Chris Lattner14553932006-01-06 07:12:35 +00004656 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnereb372a02006-01-06 07:52:12 +00004657 ShiftOp = Op0SI;
4658 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4659 // If this is a noop-integer case of a shift instruction, use the shift.
4660 if (CI->getOperand(0)->getType()->isInteger() &&
4661 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4662 CI->getType()->getPrimitiveSizeInBits() &&
4663 isa<ShiftInst>(CI->getOperand(0))) {
4664 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4665 }
4666 }
4667
4668 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4669 // Find the operands and properties of the input shift. Note that the
4670 // signedness of the input shift may differ from the current shift if there
4671 // is a noop cast between the two.
4672 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4673 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004674 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnereb372a02006-01-06 07:52:12 +00004675
4676 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4677
4678 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4679 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4680
4681 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4682 if (isLeftShift == isShiftOfLeftShift) {
4683 // Do not fold these shifts if the first one is signed and the second one
4684 // is unsigned and this is a right shift. Further, don't do any folding
4685 // on them.
4686 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4687 return 0;
Chris Lattner14553932006-01-06 07:12:35 +00004688
Chris Lattnereb372a02006-01-06 07:52:12 +00004689 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4690 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4691 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner14553932006-01-06 07:12:35 +00004692
Chris Lattnereb372a02006-01-06 07:52:12 +00004693 Value *Op = ShiftOp->getOperand(0);
4694 if (isShiftOfSignedShift != isSignedShift)
4695 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4696 return new ShiftInst(I.getOpcode(), Op,
4697 ConstantUInt::get(Type::UByteTy, Amt));
4698 }
4699
4700 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4701 // signed types, we can only support the (A >> c1) << c2 configuration,
4702 // because it can not turn an arbitrary bit of A into a sign bit.
4703 if (isUnsignedShift || isLeftShift) {
4704 // Calculate bitmask for what gets shifted off the edge.
4705 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4706 if (isLeftShift)
4707 C = ConstantExpr::getShl(C, ShiftAmt1C);
4708 else
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004709 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnereb372a02006-01-06 07:52:12 +00004710
4711 Value *Op = ShiftOp->getOperand(0);
4712 if (isShiftOfSignedShift != isSignedShift)
4713 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4714
4715 Instruction *Mask =
4716 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4717 InsertNewInstBefore(Mask, I);
4718
4719 // Figure out what flavor of shift we should use...
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004720 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004721 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004722 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004723 return new ShiftInst(I.getOpcode(), Mask,
4724 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004725 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4726 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4727 // Make sure to emit an unsigned shift right, not a signed one.
4728 Mask = InsertNewInstBefore(new CastInst(Mask,
4729 Mask->getType()->getUnsignedVersion(),
4730 Op->getName()), I);
4731 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnereb372a02006-01-06 07:52:12 +00004732 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004733 InsertNewInstBefore(Mask, I);
4734 return new CastInst(Mask, I.getType());
4735 } else {
4736 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4737 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4738 }
4739 } else {
4740 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4741 Op = InsertNewInstBefore(new CastInst(Mask,
4742 I.getType()->getSignedVersion(),
4743 Mask->getName()), I);
4744 Instruction *Shift =
4745 new ShiftInst(ShiftOp->getOpcode(), Op,
4746 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4747 InsertNewInstBefore(Shift, I);
4748
4749 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4750 C = ConstantExpr::getShl(C, Op1);
4751 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4752 InsertNewInstBefore(Mask, I);
4753 return new CastInst(Mask, I.getType());
Chris Lattnereb372a02006-01-06 07:52:12 +00004754 }
4755 } else {
Chris Lattner9cbfbc22006-01-07 01:32:28 +00004756 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnereb372a02006-01-06 07:52:12 +00004757 // this case, C1 == C2 and C1 is 8, 16, or 32.
4758 if (ShiftAmt1 == ShiftAmt2) {
4759 const Type *SExtType = 0;
Chris Lattner655d08f2006-04-28 22:21:41 +00004760 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnereb372a02006-01-06 07:52:12 +00004761 case 8 : SExtType = Type::SByteTy; break;
4762 case 16: SExtType = Type::ShortTy; break;
4763 case 32: SExtType = Type::IntTy; break;
4764 }
4765
4766 if (SExtType) {
4767 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4768 SExtType, "sext");
4769 InsertNewInstBefore(NewTrunc, I);
4770 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00004771 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00004772 }
Chris Lattner86102b82005-01-01 16:22:27 +00004773 }
Chris Lattnereb372a02006-01-06 07:52:12 +00004774 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00004775 return 0;
4776}
4777
Chris Lattner48a44f72002-05-02 17:06:02 +00004778
Chris Lattner8f663e82005-10-29 04:36:15 +00004779/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4780/// expression. If so, decompose it, returning some value X, such that Val is
4781/// X*Scale+Offset.
4782///
4783static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4784 unsigned &Offset) {
4785 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4786 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4787 Offset = CI->getValue();
4788 Scale = 1;
4789 return ConstantUInt::get(Type::UIntTy, 0);
4790 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4791 if (I->getNumOperands() == 2) {
4792 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4793 if (I->getOpcode() == Instruction::Shl) {
4794 // This is a value scaled by '1 << the shift amt'.
4795 Scale = 1U << CUI->getValue();
4796 Offset = 0;
4797 return I->getOperand(0);
4798 } else if (I->getOpcode() == Instruction::Mul) {
4799 // This value is scaled by 'CUI'.
4800 Scale = CUI->getValue();
4801 Offset = 0;
4802 return I->getOperand(0);
4803 } else if (I->getOpcode() == Instruction::Add) {
4804 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4805 // divisible by C2.
4806 unsigned SubScale;
4807 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4808 Offset);
4809 Offset += CUI->getValue();
4810 if (SubScale > 1 && (Offset % SubScale == 0)) {
4811 Scale = SubScale;
4812 return SubVal;
4813 }
4814 }
4815 }
4816 }
4817 }
4818
4819 // Otherwise, we can't look past this.
4820 Scale = 1;
4821 Offset = 0;
4822 return Val;
4823}
4824
4825
Chris Lattner216be912005-10-24 06:03:58 +00004826/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4827/// try to eliminate the cast by moving the type information into the alloc.
4828Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4829 AllocationInst &AI) {
4830 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00004831 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00004832
Chris Lattnerac87beb2005-10-24 06:22:12 +00004833 // Remove any uses of AI that are dead.
4834 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4835 std::vector<Instruction*> DeadUsers;
4836 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4837 Instruction *User = cast<Instruction>(*UI++);
4838 if (isInstructionTriviallyDead(User)) {
4839 while (UI != E && *UI == User)
4840 ++UI; // If this instruction uses AI more than once, don't break UI.
4841
4842 // Add operands to the worklist.
4843 AddUsesToWorkList(*User);
4844 ++NumDeadInst;
4845 DEBUG(std::cerr << "IC: DCE: " << *User);
4846
4847 User->eraseFromParent();
4848 removeFromWorkList(User);
4849 }
4850 }
4851
Chris Lattner216be912005-10-24 06:03:58 +00004852 // Get the type really allocated and the type casted to.
4853 const Type *AllocElTy = AI.getAllocatedType();
4854 const Type *CastElTy = PTy->getElementType();
4855 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004856
4857 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4858 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4859 if (CastElTyAlign < AllocElTyAlign) return 0;
4860
Chris Lattner46705b22005-10-24 06:35:18 +00004861 // If the allocation has multiple uses, only promote it if we are strictly
4862 // increasing the alignment of the resultant allocation. If we keep it the
4863 // same, we open the door to infinite loops of various kinds.
4864 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4865
Chris Lattner216be912005-10-24 06:03:58 +00004866 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4867 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00004868 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00004869
Chris Lattner8270c332005-10-29 03:19:53 +00004870 // See if we can satisfy the modulus by pulling a scale out of the array
4871 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00004872 unsigned ArraySizeScale, ArrayOffset;
4873 Value *NumElements = // See if the array size is a decomposable linear expr.
4874 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4875
Chris Lattner8270c332005-10-29 03:19:53 +00004876 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4877 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00004878 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4879 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004880
Chris Lattner8270c332005-10-29 03:19:53 +00004881 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4882 Value *Amt = 0;
4883 if (Scale == 1) {
4884 Amt = NumElements;
4885 } else {
4886 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4887 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4888 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4889 else if (Scale != 1) {
4890 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4891 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00004892 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004893 }
4894
Chris Lattner8f663e82005-10-29 04:36:15 +00004895 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4896 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4897 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4898 Amt = InsertNewInstBefore(Tmp, AI);
4899 }
4900
Chris Lattner216be912005-10-24 06:03:58 +00004901 std::string Name = AI.getName(); AI.setName("");
4902 AllocationInst *New;
4903 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00004904 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004905 else
Nate Begeman848622f2005-11-05 09:21:28 +00004906 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattner216be912005-10-24 06:03:58 +00004907 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00004908
4909 // If the allocation has multiple uses, insert a cast and change all things
4910 // that used it to use the new cast. This will also hack on CI, but it will
4911 // die soon.
4912 if (!AI.hasOneUse()) {
4913 AddUsesToWorkList(AI);
4914 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4915 InsertNewInstBefore(NewCast, AI);
4916 AI.replaceAllUsesWith(NewCast);
4917 }
Chris Lattner216be912005-10-24 06:03:58 +00004918 return ReplaceInstUsesWith(CI, New);
4919}
4920
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004921/// CanEvaluateInDifferentType - Return true if we can take the specified value
4922/// and return it without inserting any new casts. This is used by code that
4923/// tries to decide whether promoting or shrinking integer operations to wider
4924/// or smaller types will allow us to eliminate a truncate or extend.
4925static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
4926 int &NumCastsRemoved) {
4927 if (isa<Constant>(V)) return true;
4928
4929 Instruction *I = dyn_cast<Instruction>(V);
4930 if (!I || !I->hasOneUse()) return false;
4931
4932 switch (I->getOpcode()) {
4933 case Instruction::And:
4934 case Instruction::Or:
4935 case Instruction::Xor:
4936 // These operators can all arbitrarily be extended or truncated.
4937 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
4938 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
4939 case Instruction::Cast:
4940 // If this is a cast from the destination type, we can trivially eliminate
4941 // it, and this will remove a cast overall.
4942 if (I->getOperand(0)->getType() == Ty) {
Chris Lattner3fda3862006-06-28 17:34:50 +00004943 // If the first operand is itself a cast, and is eliminable, do not count
4944 // this as an eliminable cast. We would prefer to eliminate those two
4945 // casts first.
4946 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
4947 return true;
4948
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004949 ++NumCastsRemoved;
4950 return true;
4951 }
4952 // TODO: Can handle more cases here.
4953 break;
4954 }
4955
4956 return false;
4957}
4958
4959/// EvaluateInDifferentType - Given an expression that
4960/// CanEvaluateInDifferentType returns true for, actually insert the code to
4961/// evaluate the expression.
4962Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
4963 if (Constant *C = dyn_cast<Constant>(V))
4964 return ConstantExpr::getCast(C, Ty);
4965
4966 // Otherwise, it must be an instruction.
4967 Instruction *I = cast<Instruction>(V);
Chris Lattnerd0622b62006-05-20 23:14:03 +00004968 Instruction *Res = 0;
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00004969 switch (I->getOpcode()) {
4970 case Instruction::And:
4971 case Instruction::Or:
4972 case Instruction::Xor: {
4973 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
4974 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
4975 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
4976 LHS, RHS, I->getName());
4977 break;
4978 }
4979 case Instruction::Cast:
4980 // If this is a cast from the destination type, return the input.
4981 if (I->getOperand(0)->getType() == Ty)
4982 return I->getOperand(0);
4983
4984 // TODO: Can handle more cases here.
4985 assert(0 && "Unreachable!");
4986 break;
4987 }
4988
4989 return InsertNewInstBefore(Res, *I);
4990}
4991
Chris Lattner216be912005-10-24 06:03:58 +00004992
Chris Lattner48a44f72002-05-02 17:06:02 +00004993// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00004994//
Chris Lattner113f4f42002-06-25 16:13:24 +00004995Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00004996 Value *Src = CI.getOperand(0);
4997
Chris Lattner48a44f72002-05-02 17:06:02 +00004998 // If the user is casting a value to the same type, eliminate this cast
4999 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00005000 if (CI.getType() == Src->getType())
5001 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00005002
Chris Lattner81a7a232004-10-16 18:11:37 +00005003 if (isa<UndefValue>(Src)) // cast undef -> undef
5004 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5005
Chris Lattner48a44f72002-05-02 17:06:02 +00005006 // If casting the result of another cast instruction, try to eliminate this
5007 // one!
5008 //
Chris Lattner86102b82005-01-01 16:22:27 +00005009 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5010 Value *A = CSrc->getOperand(0);
5011 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5012 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00005013 // This instruction now refers directly to the cast's src operand. This
5014 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00005015 CI.setOperand(0, CSrc->getOperand(0));
5016 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00005017 }
5018
Chris Lattner650b6da2002-08-02 20:00:25 +00005019 // If this is an A->B->A cast, and we are dealing with integral types, try
5020 // to convert this into a logical 'and' instruction.
5021 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00005022 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00005023 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00005024 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005025 CSrc->getType()->getPrimitiveSizeInBits() <
5026 CI.getType()->getPrimitiveSizeInBits()&&
5027 A->getType()->getPrimitiveSizeInBits() ==
5028 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00005029 assert(CSrc->getType() != Type::ULongTy &&
5030 "Cannot have type bigger than ulong!");
Chris Lattner77defba2006-02-07 07:00:41 +00005031 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner86102b82005-01-01 16:22:27 +00005032 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5033 AndValue);
5034 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5035 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5036 if (And->getType() != CI.getType()) {
5037 And->setName(CSrc->getName()+".mask");
5038 InsertNewInstBefore(And, CI);
5039 And = new CastInst(And, CI.getType());
5040 }
5041 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00005042 }
5043 }
Chris Lattner2590e512006-02-07 06:56:34 +00005044
Chris Lattner03841652004-05-25 04:29:21 +00005045 // If this is a cast to bool, turn it into the appropriate setne instruction.
5046 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005047 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00005048 Constant::getNullValue(CI.getOperand(0)->getType()));
5049
Chris Lattner2590e512006-02-07 06:56:34 +00005050 // See if we can simplify any instructions used by the LHS whose sole
5051 // purpose is to compute bits we don't care about.
Chris Lattner0157e7f2006-02-11 09:31:47 +00005052 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5053 uint64_t KnownZero, KnownOne;
5054 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5055 KnownZero, KnownOne))
5056 return &CI;
5057 }
Chris Lattner2590e512006-02-07 06:56:34 +00005058
Chris Lattnerd0d51602003-06-21 23:12:02 +00005059 // If casting the result of a getelementptr instruction with no offset, turn
5060 // this into a cast of the original pointer!
5061 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00005062 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00005063 bool AllZeroOperands = true;
5064 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5065 if (!isa<Constant>(GEP->getOperand(i)) ||
5066 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5067 AllZeroOperands = false;
5068 break;
5069 }
5070 if (AllZeroOperands) {
5071 CI.setOperand(0, GEP->getOperand(0));
5072 return &CI;
5073 }
5074 }
5075
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005076 // If we are casting a malloc or alloca to a pointer to a type of the same
5077 // size, rewrite the allocation instruction to allocate the "right" type.
5078 //
5079 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00005080 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5081 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005082
Chris Lattner86102b82005-01-01 16:22:27 +00005083 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5084 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5085 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005086 if (isa<PHINode>(Src))
5087 if (Instruction *NV = FoldOpIntoPhi(CI))
5088 return NV;
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005089
5090 // If the source and destination are pointers, and this cast is equivalent to
5091 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5092 // This can enhance SROA and other transforms that want type-safe pointers.
5093 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5094 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5095 const Type *DstTy = DstPTy->getElementType();
5096 const Type *SrcTy = SrcPTy->getElementType();
5097
5098 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5099 unsigned NumZeros = 0;
5100 while (SrcTy != DstTy &&
5101 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
5102 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5103 ++NumZeros;
5104 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00005105
Chris Lattnerb19a5c62006-04-12 18:09:35 +00005106 // If we found a path from the src to dest, create the getelementptr now.
5107 if (SrcTy == DstTy) {
5108 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5109 return new GetElementPtrInst(Src, Idxs);
5110 }
5111 }
5112
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005113 // If the source value is an instruction with only this use, we can attempt to
5114 // propagate the cast into the instruction. Also, only handle integral types
5115 // for now.
Chris Lattner99155be2006-05-25 23:24:33 +00005116 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +00005117 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005118 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner1ebbe6a2006-05-13 02:06:03 +00005119
5120 int NumCastsRemoved = 0;
5121 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5122 // If this cast is a truncate, evaluting in a different type always
5123 // eliminates the cast, so it is always a win. If this is a noop-cast
5124 // this just removes a noop cast which isn't pointful, but simplifies
5125 // the code. If this is a zero-extension, we need to do an AND to
5126 // maintain the clear top-part of the computation, so we require that
5127 // the input have eliminated at least one cast. If this is a sign
5128 // extension, we insert two new casts (to do the extension) so we
5129 // require that two casts have been eliminated.
5130 bool DoXForm;
5131 switch (getCastType(Src->getType(), CI.getType())) {
5132 default: assert(0 && "Unknown cast type!");
5133 case Noop:
5134 case Truncate:
5135 DoXForm = true;
5136 break;
5137 case Zeroext:
5138 DoXForm = NumCastsRemoved >= 1;
5139 break;
5140 case Signext:
5141 DoXForm = NumCastsRemoved >= 2;
5142 break;
5143 }
5144
5145 if (DoXForm) {
5146 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5147 assert(Res->getType() == CI.getType());
5148 switch (getCastType(Src->getType(), CI.getType())) {
5149 default: assert(0 && "Unknown cast type!");
5150 case Noop:
5151 case Truncate:
5152 // Just replace this cast with the result.
5153 return ReplaceInstUsesWith(CI, Res);
5154 case Zeroext: {
5155 // We need to emit an AND to clear the high bits.
5156 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5157 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5158 assert(SrcBitSize < DestBitSize && "Not a zext?");
5159 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5160 C = ConstantExpr::getCast(C, CI.getType());
5161 return BinaryOperator::createAnd(Res, C);
5162 }
5163 case Signext:
5164 // We need to emit a cast to truncate, then a cast to sext.
5165 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5166 CI.getType());
5167 }
5168 }
5169 }
5170
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005171 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00005172 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5173 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005174
5175 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5176 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5177
5178 switch (SrcI->getOpcode()) {
5179 case Instruction::Add:
5180 case Instruction::Mul:
5181 case Instruction::And:
5182 case Instruction::Or:
5183 case Instruction::Xor:
5184 // If we are discarding information, or just changing the sign, rewrite.
5185 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5186 // Don't insert two casts if they cannot be eliminated. We allow two
5187 // casts to be inserted if the sizes are the same. This could only be
5188 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00005189 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5190 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005191 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5192 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5193 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5194 ->getOpcode(), Op0c, Op1c);
5195 }
5196 }
Chris Lattner72086162005-05-06 02:07:39 +00005197
5198 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5199 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5200 Op1 == ConstantBool::True &&
5201 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5202 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5203 return BinaryOperator::createXor(New,
5204 ConstantInt::get(CI.getType(), 1));
5205 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005206 break;
5207 case Instruction::Shl:
5208 // Allow changing the sign of the source operand. Do not allow changing
5209 // the size of the shift, UNLESS the shift amount is a constant. We
5210 // mush not change variable sized shifts to a smaller size, because it
5211 // is undefined to shift more bits out than exist in the value.
5212 if (DestBitSize == SrcBitSize ||
5213 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5214 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5215 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5216 }
5217 break;
Chris Lattner87380412005-05-06 04:18:52 +00005218 case Instruction::Shr:
5219 // If this is a signed shr, and if all bits shifted in are about to be
5220 // truncated off, turn it into an unsigned shr to allow greater
5221 // simplifications.
5222 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5223 isa<ConstantInt>(Op1)) {
5224 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5225 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5226 // Convert to unsigned.
5227 Value *N1 = InsertOperandCastBefore(Op0,
5228 Op0->getType()->getUnsignedVersion(), &CI);
5229 // Insert the new shift, which is now unsigned.
5230 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5231 Op1, Src->getName()), CI);
5232 return new CastInst(N1, CI.getType());
5233 }
5234 }
5235 break;
5236
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005237 case Instruction::SetEQ:
Chris Lattner809dfac2005-05-04 19:10:26 +00005238 case Instruction::SetNE:
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005239 // We if we are just checking for a seteq of a single bit and casting it
5240 // to an integer. If so, shift the bit to the appropriate place then
5241 // cast to integer to avoid the comparison.
Chris Lattner809dfac2005-05-04 19:10:26 +00005242 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005243 uint64_t Op1CV = Op1C->getZExtValue();
5244 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5245 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5246 // cast (X == 1) to int --> X iff X has only the low bit set.
5247 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5248 // cast (X != 0) to int --> X iff X has only the low bit set.
5249 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5250 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5251 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5252 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5253 // If Op1C some other power of two, convert:
5254 uint64_t KnownZero, KnownOne;
5255 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5256 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5257
5258 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5259 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5260 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5261 // (X&4) == 2 --> false
5262 // (X&4) != 2 --> true
Chris Lattnerc5b6c9a2006-02-28 19:47:20 +00005263 Constant *Res = ConstantBool::get(isSetNE);
5264 Res = ConstantExpr::getCast(Res, CI.getType());
5265 return ReplaceInstUsesWith(CI, Res);
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005266 }
5267
5268 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5269 Value *In = Op0;
5270 if (ShiftAmt) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00005271 // Perform an unsigned shr by shiftamt. Convert input to
5272 // unsigned if it is signed.
Chris Lattner4c2d3782005-05-06 01:53:19 +00005273 if (In->getType()->isSigned())
5274 In = InsertNewInstBefore(new CastInst(In,
5275 In->getType()->getUnsignedVersion(), In->getName()),CI);
5276 // Insert the shift to put the result in the low bit.
5277 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005278 ConstantInt::get(Type::UByteTy, ShiftAmt),
5279 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005280 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005281
5282 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5283 Constant *One = ConstantInt::get(In->getType(), 1);
5284 In = BinaryOperator::createXor(In, One, "tmp");
5285 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00005286 }
Chris Lattnerc7bfed02006-02-27 02:38:23 +00005287
5288 if (CI.getType() == In->getType())
5289 return ReplaceInstUsesWith(CI, In);
5290 else
5291 return new CastInst(In, CI.getType());
Chris Lattner4c2d3782005-05-06 01:53:19 +00005292 }
Chris Lattner809dfac2005-05-04 19:10:26 +00005293 }
5294 }
5295 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00005296 }
5297 }
Chris Lattner99155be2006-05-25 23:24:33 +00005298
5299 if (SrcI->hasOneUse()) {
5300 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5301 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5302 // because the inputs are known to be a vector. Check to see if this is
5303 // a cast to a vector with the same # elts.
5304 if (isa<PackedType>(CI.getType()) &&
5305 cast<PackedType>(CI.getType())->getNumElements() ==
5306 SVI->getType()->getNumElements()) {
5307 CastInst *Tmp;
5308 // If either of the operands is a cast from CI.getType(), then
5309 // evaluating the shuffle in the casted destination's type will allow
5310 // us to eliminate at least one cast.
5311 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5312 Tmp->getOperand(0)->getType() == CI.getType()) ||
5313 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner95cebb02006-06-06 22:26:02 +00005314 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner99155be2006-05-25 23:24:33 +00005315 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5316 CI.getType(), &CI);
5317 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5318 CI.getType(), &CI);
5319 // Return a new shuffle vector. Use the same element ID's, as we
5320 // know the vector types match #elts.
5321 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5322 }
5323 }
5324 }
5325 }
5326 }
Chris Lattnerbb171802005-10-27 05:53:56 +00005327
Chris Lattner260ab202002-04-18 17:39:14 +00005328 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00005329}
5330
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005331/// GetSelectFoldableOperands - We want to turn code that looks like this:
5332/// %C = or %A, %B
5333/// %D = select %cond, %C, %A
5334/// into:
5335/// %C = select %cond, %B, 0
5336/// %D = or %A, %C
5337///
5338/// Assuming that the specified instruction is an operand to the select, return
5339/// a bitmask indicating which operands of this instruction are foldable if they
5340/// equal the other incoming value of the select.
5341///
5342static unsigned GetSelectFoldableOperands(Instruction *I) {
5343 switch (I->getOpcode()) {
5344 case Instruction::Add:
5345 case Instruction::Mul:
5346 case Instruction::And:
5347 case Instruction::Or:
5348 case Instruction::Xor:
5349 return 3; // Can fold through either operand.
5350 case Instruction::Sub: // Can only fold on the amount subtracted.
5351 case Instruction::Shl: // Can only fold on the shift amount.
5352 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00005353 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005354 default:
5355 return 0; // Cannot fold
5356 }
5357}
5358
5359/// GetSelectFoldableConstant - For the same transformation as the previous
5360/// function, return the identity constant that goes into the select.
5361static Constant *GetSelectFoldableConstant(Instruction *I) {
5362 switch (I->getOpcode()) {
5363 default: assert(0 && "This cannot happen!"); abort();
5364 case Instruction::Add:
5365 case Instruction::Sub:
5366 case Instruction::Or:
5367 case Instruction::Xor:
5368 return Constant::getNullValue(I->getType());
5369 case Instruction::Shl:
5370 case Instruction::Shr:
5371 return Constant::getNullValue(Type::UByteTy);
5372 case Instruction::And:
5373 return ConstantInt::getAllOnesValue(I->getType());
5374 case Instruction::Mul:
5375 return ConstantInt::get(I->getType(), 1);
5376 }
5377}
5378
Chris Lattner411336f2005-01-19 21:50:18 +00005379/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5380/// have the same opcode and only one use each. Try to simplify this.
5381Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5382 Instruction *FI) {
5383 if (TI->getNumOperands() == 1) {
5384 // If this is a non-volatile load or a cast from the same type,
5385 // merge.
5386 if (TI->getOpcode() == Instruction::Cast) {
5387 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5388 return 0;
5389 } else {
5390 return 0; // unknown unary op.
5391 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005392
Chris Lattner411336f2005-01-19 21:50:18 +00005393 // Fold this by inserting a select from the input values.
5394 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5395 FI->getOperand(0), SI.getName()+".v");
5396 InsertNewInstBefore(NewSI, SI);
5397 return new CastInst(NewSI, TI->getType());
5398 }
5399
5400 // Only handle binary operators here.
5401 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5402 return 0;
5403
5404 // Figure out if the operations have any operands in common.
5405 Value *MatchOp, *OtherOpT, *OtherOpF;
5406 bool MatchIsOpZero;
5407 if (TI->getOperand(0) == FI->getOperand(0)) {
5408 MatchOp = TI->getOperand(0);
5409 OtherOpT = TI->getOperand(1);
5410 OtherOpF = FI->getOperand(1);
5411 MatchIsOpZero = true;
5412 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5413 MatchOp = TI->getOperand(1);
5414 OtherOpT = TI->getOperand(0);
5415 OtherOpF = FI->getOperand(0);
5416 MatchIsOpZero = false;
5417 } else if (!TI->isCommutative()) {
5418 return 0;
5419 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5420 MatchOp = TI->getOperand(0);
5421 OtherOpT = TI->getOperand(1);
5422 OtherOpF = FI->getOperand(0);
5423 MatchIsOpZero = true;
5424 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5425 MatchOp = TI->getOperand(1);
5426 OtherOpT = TI->getOperand(0);
5427 OtherOpF = FI->getOperand(1);
5428 MatchIsOpZero = true;
5429 } else {
5430 return 0;
5431 }
5432
5433 // If we reach here, they do have operations in common.
5434 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5435 OtherOpF, SI.getName()+".v");
5436 InsertNewInstBefore(NewSI, SI);
5437
5438 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5439 if (MatchIsOpZero)
5440 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5441 else
5442 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5443 } else {
5444 if (MatchIsOpZero)
5445 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5446 else
5447 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5448 }
5449}
5450
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005451Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00005452 Value *CondVal = SI.getCondition();
5453 Value *TrueVal = SI.getTrueValue();
5454 Value *FalseVal = SI.getFalseValue();
5455
5456 // select true, X, Y -> X
5457 // select false, X, Y -> Y
5458 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005459 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00005460 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005461 else {
5462 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00005463 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005464 }
Chris Lattner533bc492004-03-30 19:37:13 +00005465
5466 // select C, X, X -> X
5467 if (TrueVal == FalseVal)
5468 return ReplaceInstUsesWith(SI, TrueVal);
5469
Chris Lattner81a7a232004-10-16 18:11:37 +00005470 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5471 return ReplaceInstUsesWith(SI, FalseVal);
5472 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5473 return ReplaceInstUsesWith(SI, TrueVal);
5474 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5475 if (isa<Constant>(TrueVal))
5476 return ReplaceInstUsesWith(SI, TrueVal);
5477 else
5478 return ReplaceInstUsesWith(SI, FalseVal);
5479 }
5480
Chris Lattner1c631e82004-04-08 04:43:23 +00005481 if (SI.getType() == Type::BoolTy)
5482 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5483 if (C == ConstantBool::True) {
5484 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005485 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005486 } else {
5487 // Change: A = select B, false, C --> A = and !B, C
5488 Value *NotCond =
5489 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5490 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005491 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005492 }
5493 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5494 if (C == ConstantBool::False) {
5495 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005496 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005497 } else {
5498 // Change: A = select B, C, true --> A = or !B, C
5499 Value *NotCond =
5500 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5501 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005502 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00005503 }
5504 }
5505
Chris Lattner183b3362004-04-09 19:05:30 +00005506 // Selecting between two integer constants?
5507 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5508 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5509 // select C, 1, 0 -> cast C to int
5510 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5511 return new CastInst(CondVal, SI.getType());
5512 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5513 // select C, 0, 1 -> cast !C to int
5514 Value *NotCond =
5515 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00005516 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00005517 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00005518 }
Chris Lattner35167c32004-06-09 07:59:58 +00005519
5520 // If one of the constants is zero (we know they can't both be) and we
5521 // have a setcc instruction with zero, and we have an 'and' with the
5522 // non-constant value, eliminate this whole mess. This corresponds to
5523 // cases like this: ((X & 27) ? 27 : 0)
5524 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5525 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5526 if ((IC->getOpcode() == Instruction::SetEQ ||
5527 IC->getOpcode() == Instruction::SetNE) &&
5528 isa<ConstantInt>(IC->getOperand(1)) &&
5529 cast<Constant>(IC->getOperand(1))->isNullValue())
5530 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5531 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005532 isa<ConstantInt>(ICA->getOperand(1)) &&
5533 (ICA->getOperand(1) == TrueValC ||
5534 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00005535 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5536 // Okay, now we know that everything is set up, we just don't
5537 // know whether we have a setne or seteq and whether the true or
5538 // false val is the zero.
5539 bool ShouldNotVal = !TrueValC->isNullValue();
5540 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5541 Value *V = ICA;
5542 if (ShouldNotVal)
5543 V = InsertNewInstBefore(BinaryOperator::create(
5544 Instruction::Xor, V, ICA->getOperand(1)), SI);
5545 return ReplaceInstUsesWith(SI, V);
5546 }
Chris Lattner533bc492004-03-30 19:37:13 +00005547 }
Chris Lattner623fba12004-04-10 22:21:27 +00005548
5549 // See if we are selecting two values based on a comparison of the two values.
5550 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5551 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5552 // Transform (X == Y) ? X : Y -> Y
5553 if (SCI->getOpcode() == Instruction::SetEQ)
5554 return ReplaceInstUsesWith(SI, FalseVal);
5555 // Transform (X != Y) ? X : Y -> X
5556 if (SCI->getOpcode() == Instruction::SetNE)
5557 return ReplaceInstUsesWith(SI, TrueVal);
5558 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5559
5560 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5561 // Transform (X == Y) ? Y : X -> X
5562 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00005563 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005564 // Transform (X != Y) ? Y : X -> Y
5565 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00005566 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00005567 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5568 }
5569 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005570
Chris Lattnera04c9042005-01-13 22:52:24 +00005571 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5572 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5573 if (TI->hasOneUse() && FI->hasOneUse()) {
5574 bool isInverse = false;
5575 Instruction *AddOp = 0, *SubOp = 0;
5576
Chris Lattner411336f2005-01-19 21:50:18 +00005577 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5578 if (TI->getOpcode() == FI->getOpcode())
5579 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5580 return IV;
5581
5582 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5583 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00005584 if (TI->getOpcode() == Instruction::Sub &&
5585 FI->getOpcode() == Instruction::Add) {
5586 AddOp = FI; SubOp = TI;
5587 } else if (FI->getOpcode() == Instruction::Sub &&
5588 TI->getOpcode() == Instruction::Add) {
5589 AddOp = TI; SubOp = FI;
5590 }
5591
5592 if (AddOp) {
5593 Value *OtherAddOp = 0;
5594 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5595 OtherAddOp = AddOp->getOperand(1);
5596 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5597 OtherAddOp = AddOp->getOperand(0);
5598 }
5599
5600 if (OtherAddOp) {
Chris Lattnerb580d262006-02-24 18:05:58 +00005601 // So at this point we know we have (Y -> OtherAddOp):
5602 // select C, (add X, Y), (sub X, Z)
5603 Value *NegVal; // Compute -Z
5604 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5605 NegVal = ConstantExpr::getNeg(C);
5606 } else {
5607 NegVal = InsertNewInstBefore(
5608 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattnera04c9042005-01-13 22:52:24 +00005609 }
Chris Lattnerb580d262006-02-24 18:05:58 +00005610
5611 Value *NewTrueOp = OtherAddOp;
5612 Value *NewFalseOp = NegVal;
5613 if (AddOp != TI)
5614 std::swap(NewTrueOp, NewFalseOp);
5615 Instruction *NewSel =
5616 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5617
5618 NewSel = InsertNewInstBefore(NewSel, SI);
5619 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00005620 }
5621 }
5622 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005623
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005624 // See if we can fold the select into one of our operands.
5625 if (SI.getType()->isInteger()) {
5626 // See the comment above GetSelectFoldableOperands for a description of the
5627 // transformation we are doing here.
5628 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5629 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5630 !isa<Constant>(FalseVal))
5631 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5632 unsigned OpToFold = 0;
5633 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5634 OpToFold = 1;
5635 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5636 OpToFold = 2;
5637 }
5638
5639 if (OpToFold) {
5640 Constant *C = GetSelectFoldableConstant(TVI);
5641 std::string Name = TVI->getName(); TVI->setName("");
5642 Instruction *NewSel =
5643 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5644 Name);
5645 InsertNewInstBefore(NewSel, SI);
5646 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5647 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5648 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5649 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5650 else {
5651 assert(0 && "Unknown instruction!!");
5652 }
5653 }
5654 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00005655
Chris Lattner56e4d3d2004-04-09 23:46:01 +00005656 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5657 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5658 !isa<Constant>(TrueVal))
5659 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5660 unsigned OpToFold = 0;
5661 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5662 OpToFold = 1;
5663 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5664 OpToFold = 2;
5665 }
5666
5667 if (OpToFold) {
5668 Constant *C = GetSelectFoldableConstant(FVI);
5669 std::string Name = FVI->getName(); FVI->setName("");
5670 Instruction *NewSel =
5671 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5672 Name);
5673 InsertNewInstBefore(NewSel, SI);
5674 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5675 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5676 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5677 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5678 else {
5679 assert(0 && "Unknown instruction!!");
5680 }
5681 }
5682 }
5683 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00005684
5685 if (BinaryOperator::isNot(CondVal)) {
5686 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5687 SI.setOperand(1, FalseVal);
5688 SI.setOperand(2, TrueVal);
5689 return &SI;
5690 }
5691
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005692 return 0;
5693}
5694
Chris Lattner82f2ef22006-03-06 20:18:44 +00005695/// GetKnownAlignment - If the specified pointer has an alignment that we can
5696/// determine, return it, otherwise return 0.
5697static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5698 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5699 unsigned Align = GV->getAlignment();
5700 if (Align == 0 && TD)
5701 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5702 return Align;
5703 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5704 unsigned Align = AI->getAlignment();
5705 if (Align == 0 && TD) {
5706 if (isa<AllocaInst>(AI))
5707 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5708 else if (isa<MallocInst>(AI)) {
5709 // Malloc returns maximally aligned memory.
5710 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5711 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5712 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5713 }
5714 }
5715 return Align;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005716 } else if (isa<CastInst>(V) ||
5717 (isa<ConstantExpr>(V) &&
5718 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5719 User *CI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005720 if (isa<PointerType>(CI->getOperand(0)->getType()))
5721 return GetKnownAlignment(CI->getOperand(0), TD);
5722 return 0;
Chris Lattner53ef5a02006-03-07 01:28:57 +00005723 } else if (isa<GetElementPtrInst>(V) ||
5724 (isa<ConstantExpr>(V) &&
5725 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5726 User *GEPI = cast<User>(V);
Chris Lattner82f2ef22006-03-06 20:18:44 +00005727 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5728 if (BaseAlignment == 0) return 0;
5729
5730 // If all indexes are zero, it is just the alignment of the base pointer.
5731 bool AllZeroOperands = true;
5732 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5733 if (!isa<Constant>(GEPI->getOperand(i)) ||
5734 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5735 AllZeroOperands = false;
5736 break;
5737 }
5738 if (AllZeroOperands)
5739 return BaseAlignment;
5740
5741 // Otherwise, if the base alignment is >= the alignment we expect for the
5742 // base pointer type, then we know that the resultant pointer is aligned at
5743 // least as much as its type requires.
5744 if (!TD) return 0;
5745
5746 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5747 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner53ef5a02006-03-07 01:28:57 +00005748 <= BaseAlignment) {
5749 const Type *GEPTy = GEPI->getType();
5750 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5751 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005752 return 0;
5753 }
5754 return 0;
5755}
5756
Chris Lattnerb909e8b2004-03-12 05:52:32 +00005757
Chris Lattnerc66b2232006-01-13 20:11:04 +00005758/// visitCallInst - CallInst simplification. This mostly only handles folding
5759/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5760/// the heavy lifting.
5761///
Chris Lattner970c33a2003-06-19 17:00:31 +00005762Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattnerc66b2232006-01-13 20:11:04 +00005763 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5764 if (!II) return visitCallSite(&CI);
5765
Chris Lattner51ea1272004-02-28 05:22:00 +00005766 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5767 // visitCallSite.
Chris Lattnerc66b2232006-01-13 20:11:04 +00005768 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005769 bool Changed = false;
5770
5771 // memmove/cpy/set of zero bytes is a noop.
5772 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5773 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5774
Chris Lattner00648e12004-10-12 04:52:52 +00005775 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5776 if (CI->getRawValue() == 1) {
5777 // Replace the instruction with just byte operations. We would
5778 // transform other cases to loads/stores, but we don't know if
5779 // alignment is sufficient.
5780 }
Chris Lattner51ea1272004-02-28 05:22:00 +00005781 }
5782
Chris Lattner00648e12004-10-12 04:52:52 +00005783 // If we have a memmove and the source operation is a constant global,
5784 // then the source and dest pointers can't alias, so we can change this
5785 // into a call to memcpy.
Chris Lattner82f2ef22006-03-06 20:18:44 +00005786 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner00648e12004-10-12 04:52:52 +00005787 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5788 if (GVSrc->isConstant()) {
5789 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner681ef2f2006-03-03 01:34:17 +00005790 const char *Name;
5791 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5792 Type::UIntTy)
5793 Name = "llvm.memcpy.i32";
5794 else
5795 Name = "llvm.memcpy.i64";
5796 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner00648e12004-10-12 04:52:52 +00005797 CI.getCalledFunction()->getFunctionType());
5798 CI.setOperand(0, MemCpy);
5799 Changed = true;
5800 }
Chris Lattner82f2ef22006-03-06 20:18:44 +00005801 }
Chris Lattner00648e12004-10-12 04:52:52 +00005802
Chris Lattner82f2ef22006-03-06 20:18:44 +00005803 // If we can determine a pointer alignment that is bigger than currently
5804 // set, update the alignment.
5805 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5806 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5807 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5808 unsigned Align = std::min(Alignment1, Alignment2);
5809 if (MI->getAlignment()->getRawValue() < Align) {
5810 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5811 Changed = true;
5812 }
5813 } else if (isa<MemSetInst>(MI)) {
5814 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5815 if (MI->getAlignment()->getRawValue() < Alignment) {
5816 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5817 Changed = true;
5818 }
5819 }
5820
Chris Lattnerc66b2232006-01-13 20:11:04 +00005821 if (Changed) return II;
Chris Lattner503221f2006-01-13 21:28:09 +00005822 } else {
5823 switch (II->getIntrinsicID()) {
5824 default: break;
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005825 case Intrinsic::ppc_altivec_lvx:
5826 case Intrinsic::ppc_altivec_lvxl:
Chris Lattner36dd7c92006-04-17 22:26:56 +00005827 case Intrinsic::x86_sse_loadu_ps:
5828 case Intrinsic::x86_sse2_loadu_pd:
5829 case Intrinsic::x86_sse2_loadu_dq:
5830 // Turn PPC lvx -> load if the pointer is known aligned.
5831 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005832 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005833 Value *Ptr = InsertCastBefore(II->getOperand(1),
5834 PointerType::get(II->getType()), CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005835 return new LoadInst(Ptr);
5836 }
5837 break;
5838 case Intrinsic::ppc_altivec_stvx:
5839 case Intrinsic::ppc_altivec_stvxl:
5840 // Turn stvx -> store if the pointer is known aligned.
5841 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere79d2492006-04-06 19:19:17 +00005842 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5843 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattnerf42d0ae2006-04-02 05:30:25 +00005844 return new StoreInst(II->getOperand(1), Ptr);
5845 }
5846 break;
Chris Lattner36dd7c92006-04-17 22:26:56 +00005847 case Intrinsic::x86_sse_storeu_ps:
5848 case Intrinsic::x86_sse2_storeu_pd:
5849 case Intrinsic::x86_sse2_storeu_dq:
5850 case Intrinsic::x86_sse2_storel_dq:
5851 // Turn X86 storeu -> store if the pointer is known aligned.
5852 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5853 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5854 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5855 return new StoreInst(II->getOperand(2), Ptr);
5856 }
5857 break;
Chris Lattnere79d2492006-04-06 19:19:17 +00005858 case Intrinsic::ppc_altivec_vperm:
5859 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5860 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5861 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5862
5863 // Check that all of the elements are integer constants or undefs.
5864 bool AllEltsOk = true;
5865 for (unsigned i = 0; i != 16; ++i) {
5866 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5867 !isa<UndefValue>(Mask->getOperand(i))) {
5868 AllEltsOk = false;
5869 break;
5870 }
5871 }
5872
5873 if (AllEltsOk) {
5874 // Cast the input vectors to byte vectors.
5875 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5876 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5877 Value *Result = UndefValue::get(Op0->getType());
5878
5879 // Only extract each element once.
5880 Value *ExtractedElts[32];
5881 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5882
5883 for (unsigned i = 0; i != 16; ++i) {
5884 if (isa<UndefValue>(Mask->getOperand(i)))
5885 continue;
5886 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5887 Idx &= 31; // Match the hardware behavior.
5888
5889 if (ExtractedElts[Idx] == 0) {
5890 Instruction *Elt =
5891 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5892 ConstantUInt::get(Type::UIntTy, Idx&15),
5893 "tmp");
5894 InsertNewInstBefore(Elt, CI);
5895 ExtractedElts[Idx] = Elt;
5896 }
5897
5898 // Insert this value into the result vector.
5899 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5900 ConstantUInt::get(Type::UIntTy, i),
5901 "tmp");
5902 InsertNewInstBefore(cast<Instruction>(Result), CI);
5903 }
5904 return new CastInst(Result, CI.getType());
5905 }
5906 }
5907 break;
5908
Chris Lattner503221f2006-01-13 21:28:09 +00005909 case Intrinsic::stackrestore: {
5910 // If the save is right next to the restore, remove the restore. This can
5911 // happen when variable allocas are DCE'd.
5912 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5913 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5914 BasicBlock::iterator BI = SS;
5915 if (&*++BI == II)
5916 return EraseInstFromFunction(CI);
5917 }
5918 }
5919
5920 // If the stack restore is in a return/unwind block and if there are no
5921 // allocas or calls between the restore and the return, nuke the restore.
5922 TerminatorInst *TI = II->getParent()->getTerminator();
5923 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5924 BasicBlock::iterator BI = II;
5925 bool CannotRemove = false;
5926 for (++BI; &*BI != TI; ++BI) {
5927 if (isa<AllocaInst>(BI) ||
5928 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5929 CannotRemove = true;
5930 break;
5931 }
5932 }
5933 if (!CannotRemove)
5934 return EraseInstFromFunction(CI);
5935 }
5936 break;
5937 }
5938 }
Chris Lattner00648e12004-10-12 04:52:52 +00005939 }
5940
Chris Lattnerc66b2232006-01-13 20:11:04 +00005941 return visitCallSite(II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005942}
5943
5944// InvokeInst simplification
5945//
5946Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00005947 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00005948}
5949
Chris Lattneraec3d942003-10-07 22:32:43 +00005950// visitCallSite - Improvements for call and invoke instructions.
5951//
5952Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005953 bool Changed = false;
5954
5955 // If the callee is a constexpr cast of a function, attempt to move the cast
5956 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00005957 if (transformConstExprCastCall(CS)) return 0;
5958
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005959 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00005960
Chris Lattner61d9d812005-05-13 07:09:09 +00005961 if (Function *CalleeF = dyn_cast<Function>(Callee))
5962 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5963 Instruction *OldCall = CS.getInstruction();
5964 // If the call and callee calling conventions don't match, this call must
5965 // be unreachable, as the call is undefined.
5966 new StoreInst(ConstantBool::True,
5967 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5968 if (!OldCall->use_empty())
5969 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5970 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5971 return EraseInstFromFunction(*OldCall);
5972 return 0;
5973 }
5974
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005975 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5976 // This instruction is not reachable, just remove it. We insert a store to
5977 // undef so that we know that this code is not reachable, despite the fact
5978 // that we can't modify the CFG here.
5979 new StoreInst(ConstantBool::True,
5980 UndefValue::get(PointerType::get(Type::BoolTy)),
5981 CS.getInstruction());
5982
5983 if (!CS.getInstruction()->use_empty())
5984 CS.getInstruction()->
5985 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5986
5987 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5988 // Don't break the CFG, insert a dummy cond branch.
5989 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5990 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00005991 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005992 return EraseInstFromFunction(*CS.getInstruction());
5993 }
Chris Lattner81a7a232004-10-16 18:11:37 +00005994
Chris Lattner75b4d1d2003-10-07 22:54:13 +00005995 const PointerType *PTy = cast<PointerType>(Callee->getType());
5996 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5997 if (FTy->isVarArg()) {
5998 // See if we can optimize any arguments passed through the varargs area of
5999 // the call.
6000 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6001 E = CS.arg_end(); I != E; ++I)
6002 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6003 // If this cast does not effect the value passed through the varargs
6004 // area, we can eliminate the use of the cast.
6005 Value *Op = CI->getOperand(0);
6006 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6007 *I = Op;
6008 Changed = true;
6009 }
6010 }
6011 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006012
Chris Lattner75b4d1d2003-10-07 22:54:13 +00006013 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00006014}
6015
Chris Lattner970c33a2003-06-19 17:00:31 +00006016// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6017// attempt to move the cast to the arguments of the call/invoke.
6018//
6019bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6020 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6021 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00006022 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00006023 return false;
Reid Spencer87436872004-07-18 00:38:32 +00006024 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00006025 Instruction *Caller = CS.getInstruction();
6026
6027 // Okay, this is a cast from a function to a different type. Unless doing so
6028 // would cause a type conversion of one of our arguments, change this call to
6029 // be a direct call with arguments casted to the appropriate types.
6030 //
6031 const FunctionType *FT = Callee->getFunctionType();
6032 const Type *OldRetTy = Caller->getType();
6033
Chris Lattner1f7942f2004-01-14 06:06:08 +00006034 // Check to see if we are changing the return type...
6035 if (OldRetTy != FT->getReturnType()) {
6036 if (Callee->isExternal() &&
Andrew Lenharth61eae292006-04-20 14:56:47 +00006037 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6038 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharthf89e6302006-04-20 15:41:37 +00006039 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth61eae292006-04-20 14:56:47 +00006040 && !Caller->use_empty())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006041 return false; // Cannot transform this return value...
6042
6043 // If the callsite is an invoke instruction, and the return value is used by
6044 // a PHI node in a successor, we cannot change the return type of the call
6045 // because there is no place to put the cast instruction (without breaking
6046 // the critical edge). Bail out in this case.
6047 if (!Caller->use_empty())
6048 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6049 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6050 UI != E; ++UI)
6051 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6052 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006053 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00006054 return false;
6055 }
Chris Lattner970c33a2003-06-19 17:00:31 +00006056
6057 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6058 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006059
Chris Lattner970c33a2003-06-19 17:00:31 +00006060 CallSite::arg_iterator AI = CS.arg_begin();
6061 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6062 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthebfa24e2006-06-28 01:01:52 +00006063 const Type *ActTy = (*AI)->getType();
6064 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6065 //Either we can cast directly, or we can upconvert the argument
6066 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6067 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6068 ParamTy->isSigned() == ActTy->isSigned() &&
6069 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6070 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6071 c->getValue() > 0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006072 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00006073 }
6074
6075 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6076 Callee->isExternal())
6077 return false; // Do not delete arguments unless we have a function body...
6078
6079 // Okay, we decided that this is a safe thing to do: go ahead and start
6080 // inserting cast instructions as necessary...
6081 std::vector<Value*> Args;
6082 Args.reserve(NumActualArgs);
6083
6084 AI = CS.arg_begin();
6085 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6086 const Type *ParamTy = FT->getParamType(i);
6087 if ((*AI)->getType() == ParamTy) {
6088 Args.push_back(*AI);
6089 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00006090 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6091 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00006092 }
6093 }
6094
6095 // If the function takes more arguments than the call was taking, add them
6096 // now...
6097 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6098 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6099
6100 // If we are removing arguments to the function, emit an obnoxious warning...
6101 if (FT->getNumParams() < NumActualArgs)
6102 if (!FT->isVarArg()) {
6103 std::cerr << "WARNING: While resolving call to function '"
6104 << Callee->getName() << "' arguments were dropped!\n";
6105 } else {
6106 // Add all of the arguments in their promoted form to the arg list...
6107 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6108 const Type *PTy = getPromotedType((*AI)->getType());
6109 if (PTy != (*AI)->getType()) {
6110 // Must promote to pass through va_arg area!
6111 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6112 InsertNewInstBefore(Cast, *Caller);
6113 Args.push_back(Cast);
6114 } else {
6115 Args.push_back(*AI);
6116 }
6117 }
6118 }
6119
6120 if (FT->getReturnType() == Type::VoidTy)
6121 Caller->setName(""); // Void type should not have a name...
6122
6123 Instruction *NC;
6124 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00006125 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00006126 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00006127 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006128 } else {
6129 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00006130 if (cast<CallInst>(Caller)->isTailCall())
6131 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00006132 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00006133 }
6134
6135 // Insert a cast of the return type as necessary...
6136 Value *NV = NC;
6137 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6138 if (NV->getType() != Type::VoidTy) {
6139 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00006140
6141 // If this is an invoke instruction, we should insert it after the first
6142 // non-phi, instruction in the normal successor block.
6143 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6144 BasicBlock::iterator I = II->getNormalDest()->begin();
6145 while (isa<PHINode>(I)) ++I;
6146 InsertNewInstBefore(NC, *I);
6147 } else {
6148 // Otherwise, it's a call, just insert cast right after the call instr
6149 InsertNewInstBefore(NC, *Caller);
6150 }
Chris Lattner51ea1272004-02-28 05:22:00 +00006151 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00006152 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00006153 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00006154 }
6155 }
6156
6157 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6158 Caller->replaceAllUsesWith(NV);
6159 Caller->getParent()->getInstList().erase(Caller);
6160 removeFromWorkList(Caller);
6161 return true;
6162}
6163
6164
Chris Lattner7515cab2004-11-14 19:13:23 +00006165// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6166// operator and they all are only used by the PHI, PHI together their
6167// inputs, and do the operation once, to the result of the PHI.
6168Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6169 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6170
6171 // Scan the instruction, looking for input operations that can be folded away.
6172 // If all input operands to the phi are the same instruction (e.g. a cast from
6173 // the same type or "+42") we can pull the operation through the PHI, reducing
6174 // code size and simplifying code.
6175 Constant *ConstantOp = 0;
6176 const Type *CastSrcTy = 0;
6177 if (isa<CastInst>(FirstInst)) {
6178 CastSrcTy = FirstInst->getOperand(0)->getType();
6179 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6180 // Can fold binop or shift if the RHS is a constant.
6181 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6182 if (ConstantOp == 0) return 0;
6183 } else {
6184 return 0; // Cannot fold this operation.
6185 }
6186
6187 // Check to see if all arguments are the same operation.
6188 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6189 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6190 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6191 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6192 return 0;
6193 if (CastSrcTy) {
6194 if (I->getOperand(0)->getType() != CastSrcTy)
6195 return 0; // Cast operation must match.
6196 } else if (I->getOperand(1) != ConstantOp) {
6197 return 0;
6198 }
6199 }
6200
6201 // Okay, they are all the same operation. Create a new PHI node of the
6202 // correct type, and PHI together all of the LHS's of the instructions.
6203 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6204 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00006205 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00006206
6207 Value *InVal = FirstInst->getOperand(0);
6208 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00006209
6210 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00006211 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6212 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6213 if (NewInVal != InVal)
6214 InVal = 0;
6215 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6216 }
6217
6218 Value *PhiVal;
6219 if (InVal) {
6220 // The new PHI unions all of the same values together. This is really
6221 // common, so we handle it intelligently here for compile-time speed.
6222 PhiVal = InVal;
6223 delete NewPN;
6224 } else {
6225 InsertNewInstBefore(NewPN, PN);
6226 PhiVal = NewPN;
6227 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006228
Chris Lattner7515cab2004-11-14 19:13:23 +00006229 // Insert and return the new operation.
6230 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006231 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00006232 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00006233 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006234 else
6235 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00006236 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00006237}
Chris Lattner48a44f72002-05-02 17:06:02 +00006238
Chris Lattner71536432005-01-17 05:10:15 +00006239/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6240/// that is dead.
6241static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6242 if (PN->use_empty()) return true;
6243 if (!PN->hasOneUse()) return false;
6244
6245 // Remember this node, and if we find the cycle, return.
6246 if (!PotentiallyDeadPHIs.insert(PN).second)
6247 return true;
6248
6249 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6250 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006251
Chris Lattner71536432005-01-17 05:10:15 +00006252 return false;
6253}
6254
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006255// PHINode simplification
6256//
Chris Lattner113f4f42002-06-25 16:13:24 +00006257Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonbbf89902006-07-10 22:15:25 +00006258 // If LCSSA is around, don't mess with Phi nodes
6259 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersona6968f82006-07-10 19:03:49 +00006260
Owen Andersonae8aa642006-07-10 22:03:18 +00006261 if (Value *V = PN.hasConstantValue())
6262 return ReplaceInstUsesWith(PN, V);
6263
6264 // If the only user of this instruction is a cast instruction, and all of the
6265 // incoming values are constants, change this PHI to merge together the casted
6266 // constants.
6267 if (PN.hasOneUse())
6268 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6269 if (CI->getType() != PN.getType()) { // noop casts will be folded
6270 bool AllConstant = true;
6271 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6272 if (!isa<Constant>(PN.getIncomingValue(i))) {
6273 AllConstant = false;
6274 break;
6275 }
6276 if (AllConstant) {
6277 // Make a new PHI with all casted values.
6278 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6279 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6280 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6281 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6282 PN.getIncomingBlock(i));
6283 }
6284
6285 // Update the cast instruction.
6286 CI->setOperand(0, New);
6287 WorkList.push_back(CI); // revisit the cast instruction to fold.
6288 WorkList.push_back(New); // Make sure to revisit the new Phi
6289 return &PN; // PN is now dead!
6290 }
6291 }
6292
6293 // If all PHI operands are the same operation, pull them through the PHI,
6294 // reducing code size.
6295 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6296 PN.getIncomingValue(0)->hasOneUse())
6297 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6298 return Result;
6299
6300 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6301 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6302 // PHI)... break the cycle.
6303 if (PN.hasOneUse())
6304 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6305 std::set<PHINode*> PotentiallyDeadPHIs;
6306 PotentiallyDeadPHIs.insert(&PN);
6307 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6308 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6309 }
6310
Chris Lattner91daeb52003-12-19 05:58:40 +00006311 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00006312}
6313
Chris Lattner69193f92004-04-05 01:30:19 +00006314static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6315 Instruction *InsertPoint,
6316 InstCombiner *IC) {
6317 unsigned PS = IC->getTargetData().getPointerSize();
6318 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00006319 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6320 // We must insert a cast to ensure we sign-extend.
6321 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6322 V->getName()), *InsertPoint);
6323 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6324 *InsertPoint);
6325}
6326
Chris Lattner48a44f72002-05-02 17:06:02 +00006327
Chris Lattner113f4f42002-06-25 16:13:24 +00006328Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006329 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00006330 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00006331 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006332 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00006333 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006334
Chris Lattner81a7a232004-10-16 18:11:37 +00006335 if (isa<UndefValue>(GEP.getOperand(0)))
6336 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6337
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006338 bool HasZeroPointerIndex = false;
6339 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6340 HasZeroPointerIndex = C->isNullValue();
6341
6342 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00006343 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00006344
Chris Lattner69193f92004-04-05 01:30:19 +00006345 // Eliminate unneeded casts for indices.
6346 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00006347 gep_type_iterator GTI = gep_type_begin(GEP);
6348 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6349 if (isa<SequentialType>(*GTI)) {
6350 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6351 Value *Src = CI->getOperand(0);
6352 const Type *SrcTy = Src->getType();
6353 const Type *DestTy = CI->getType();
6354 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006355 if (SrcTy->getPrimitiveSizeInBits() ==
6356 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006357 // We can always eliminate a cast from ulong or long to the other.
6358 // We can always eliminate a cast from uint to int or the other on
6359 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006360 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00006361 MadeChange = true;
6362 GEP.setOperand(i, Src);
6363 }
6364 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6365 SrcTy->getPrimitiveSize() == 4) {
6366 // We can always eliminate a cast from int to [u]long. We can
6367 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6368 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006369 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00006370 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006371 MadeChange = true;
6372 GEP.setOperand(i, Src);
6373 }
Chris Lattner69193f92004-04-05 01:30:19 +00006374 }
6375 }
6376 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00006377 // If we are using a wider index than needed for this platform, shrink it
6378 // to what we need. If the incoming value needs a cast instruction,
6379 // insert it. This explicit cast can make subsequent optimizations more
6380 // obvious.
6381 Value *Op = GEP.getOperand(i);
6382 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006383 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00006384 GEP.setOperand(i, ConstantExpr::getCast(C,
6385 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00006386 MadeChange = true;
6387 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00006388 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6389 Op->getName()), GEP);
6390 GEP.setOperand(i, Op);
6391 MadeChange = true;
6392 }
Chris Lattner44d0b952004-07-20 01:48:15 +00006393
6394 // If this is a constant idx, make sure to canonicalize it to be a signed
6395 // operand, otherwise CSE and other optimizations are pessimized.
6396 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6397 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6398 CUI->getType()->getSignedVersion()));
6399 MadeChange = true;
6400 }
Chris Lattner69193f92004-04-05 01:30:19 +00006401 }
6402 if (MadeChange) return &GEP;
6403
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006404 // Combine Indices - If the source pointer to this getelementptr instruction
6405 // is a getelementptr instruction, combine the indices of the two
6406 // getelementptr instructions into a single instruction.
6407 //
Chris Lattner57c67b02004-03-25 22:59:29 +00006408 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00006409 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00006410 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00006411
6412 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00006413 // Note that if our source is a gep chain itself that we wait for that
6414 // chain to be resolved before we perform this transformation. This
6415 // avoids us creating a TON of code in some cases.
6416 //
6417 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6418 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6419 return 0; // Wait until our source is folded to completion.
6420
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006421 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00006422
6423 // Find out whether the last index in the source GEP is a sequential idx.
6424 bool EndsWithSequential = false;
6425 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6426 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00006427 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006428
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006429 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00006430 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00006431 // Replace: gep (gep %P, long B), long A, ...
6432 // With: T = long A+B; gep %P, T, ...
6433 //
Chris Lattner5f667a62004-05-07 22:09:22 +00006434 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00006435 if (SO1 == Constant::getNullValue(SO1->getType())) {
6436 Sum = GO1;
6437 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6438 Sum = SO1;
6439 } else {
6440 // If they aren't the same type, convert both to an integer of the
6441 // target's pointer size.
6442 if (SO1->getType() != GO1->getType()) {
6443 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6444 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6445 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6446 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6447 } else {
6448 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00006449 if (SO1->getType()->getPrimitiveSize() == PS) {
6450 // Convert GO1 to SO1's type.
6451 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6452
6453 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6454 // Convert SO1 to GO1's type.
6455 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6456 } else {
6457 const Type *PT = TD->getIntPtrType();
6458 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6459 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6460 }
6461 }
6462 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006463 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6464 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6465 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00006466 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6467 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00006468 }
Chris Lattner69193f92004-04-05 01:30:19 +00006469 }
Chris Lattner5f667a62004-05-07 22:09:22 +00006470
6471 // Recycle the GEP we already have if possible.
6472 if (SrcGEPOperands.size() == 2) {
6473 GEP.setOperand(0, SrcGEPOperands[0]);
6474 GEP.setOperand(1, Sum);
6475 return &GEP;
6476 } else {
6477 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6478 SrcGEPOperands.end()-1);
6479 Indices.push_back(Sum);
6480 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6481 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00006482 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00006483 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006484 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006485 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00006486 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6487 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00006488 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6489 }
6490
6491 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00006492 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006493
Chris Lattner5f667a62004-05-07 22:09:22 +00006494 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006495 // GEP of global variable. If all of the indices for this GEP are
6496 // constants, we can promote this to a constexpr instead of an instruction.
6497
6498 // Scan for nonconstants...
6499 std::vector<Constant*> Indices;
6500 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6501 for (; I != E && isa<Constant>(*I); ++I)
6502 Indices.push_back(cast<Constant>(*I));
6503
6504 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00006505 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00006506
6507 // Replace all uses of the GEP with the new constexpr...
6508 return ReplaceInstUsesWith(GEP, CE);
6509 }
Chris Lattner567b81f2005-09-13 00:40:14 +00006510 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6511 if (!isa<PointerType>(X->getType())) {
6512 // Not interesting. Source pointer must be a cast from pointer.
6513 } else if (HasZeroPointerIndex) {
6514 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6515 // into : GEP [10 x ubyte]* X, long 0, ...
6516 //
6517 // This occurs when the program declares an array extern like "int X[];"
6518 //
6519 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6520 const PointerType *XTy = cast<PointerType>(X->getType());
6521 if (const ArrayType *XATy =
6522 dyn_cast<ArrayType>(XTy->getElementType()))
6523 if (const ArrayType *CATy =
6524 dyn_cast<ArrayType>(CPTy->getElementType()))
6525 if (CATy->getElementType() == XATy->getElementType()) {
6526 // At this point, we know that the cast source type is a pointer
6527 // to an array of the same type as the destination pointer
6528 // array. Because the array type is never stepped over (there
6529 // is a leading zero) we can fold the cast into this GEP.
6530 GEP.setOperand(0, X);
6531 return &GEP;
6532 }
6533 } else if (GEP.getNumOperands() == 2) {
6534 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00006535 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6536 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00006537 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6538 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6539 if (isa<ArrayType>(SrcElTy) &&
6540 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6541 TD->getTypeSize(ResElTy)) {
6542 Value *V = InsertNewInstBefore(
6543 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6544 GEP.getOperand(1), GEP.getName()), GEP);
6545 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006546 }
Chris Lattner2a893292005-09-13 18:36:04 +00006547
6548 // Transform things like:
6549 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6550 // (where tmp = 8*tmp2) into:
6551 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6552
6553 if (isa<ArrayType>(SrcElTy) &&
6554 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6555 uint64_t ArrayEltSize =
6556 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6557
6558 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6559 // allow either a mul, shift, or constant here.
6560 Value *NewIdx = 0;
6561 ConstantInt *Scale = 0;
6562 if (ArrayEltSize == 1) {
6563 NewIdx = GEP.getOperand(1);
6564 Scale = ConstantInt::get(NewIdx->getType(), 1);
6565 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00006566 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00006567 Scale = CI;
6568 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6569 if (Inst->getOpcode() == Instruction::Shl &&
6570 isa<ConstantInt>(Inst->getOperand(1))) {
6571 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6572 if (Inst->getType()->isSigned())
6573 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6574 else
6575 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6576 NewIdx = Inst->getOperand(0);
6577 } else if (Inst->getOpcode() == Instruction::Mul &&
6578 isa<ConstantInt>(Inst->getOperand(1))) {
6579 Scale = cast<ConstantInt>(Inst->getOperand(1));
6580 NewIdx = Inst->getOperand(0);
6581 }
6582 }
6583
6584 // If the index will be to exactly the right offset with the scale taken
6585 // out, perform the transformation.
6586 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6587 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6588 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00006589 (int64_t)C->getRawValue() /
6590 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00006591 else
6592 Scale = ConstantUInt::get(Scale->getType(),
6593 Scale->getRawValue() / ArrayEltSize);
6594 if (Scale->getRawValue() != 1) {
6595 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6596 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6597 NewIdx = InsertNewInstBefore(Sc, GEP);
6598 }
6599
6600 // Insert the new GEP instruction.
6601 Instruction *Idx =
6602 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6603 NewIdx, GEP.getName());
6604 Idx = InsertNewInstBefore(Idx, GEP);
6605 return new CastInst(Idx, GEP.getType());
6606 }
6607 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00006608 }
Chris Lattnerca081252001-12-14 16:52:21 +00006609 }
6610
Chris Lattnerca081252001-12-14 16:52:21 +00006611 return 0;
6612}
6613
Chris Lattner1085bdf2002-11-04 16:18:53 +00006614Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6615 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6616 if (AI.isArrayAllocation()) // Check C != 1
6617 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6618 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006619 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00006620
6621 // Create and insert the replacement instruction...
6622 if (isa<MallocInst>(AI))
Nate Begeman848622f2005-11-05 09:21:28 +00006623 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006624 else {
6625 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman848622f2005-11-05 09:21:28 +00006626 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00006627 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006628
6629 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00006630
Chris Lattner1085bdf2002-11-04 16:18:53 +00006631 // Scan to the end of the allocation instructions, to skip over a block of
6632 // allocas if possible...
6633 //
6634 BasicBlock::iterator It = New;
6635 while (isa<AllocationInst>(*It)) ++It;
6636
6637 // Now that I is pointing to the first non-allocation-inst in the block,
6638 // insert our getelementptr instruction...
6639 //
Chris Lattner809dfac2005-05-04 19:10:26 +00006640 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6641 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6642 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00006643
6644 // Now make everything use the getelementptr instead of the original
6645 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00006646 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00006647 } else if (isa<UndefValue>(AI.getArraySize())) {
6648 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00006649 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00006650
6651 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6652 // Note that we only do this for alloca's, because malloc should allocate and
6653 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00006654 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00006655 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00006656 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6657
Chris Lattner1085bdf2002-11-04 16:18:53 +00006658 return 0;
6659}
6660
Chris Lattner8427bff2003-12-07 01:24:23 +00006661Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6662 Value *Op = FI.getOperand(0);
6663
6664 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6665 if (CastInst *CI = dyn_cast<CastInst>(Op))
6666 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6667 FI.setOperand(0, CI->getOperand(0));
6668 return &FI;
6669 }
6670
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006671 // free undef -> unreachable.
6672 if (isa<UndefValue>(Op)) {
6673 // Insert a new store to null because we cannot modify the CFG here.
6674 new StoreInst(ConstantBool::True,
6675 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6676 return EraseInstFromFunction(FI);
6677 }
6678
Chris Lattnerf3a36602004-02-28 04:57:37 +00006679 // If we have 'free null' delete the instruction. This can happen in stl code
6680 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006681 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00006682 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00006683
Chris Lattner8427bff2003-12-07 01:24:23 +00006684 return 0;
6685}
6686
6687
Chris Lattner72684fe2005-01-31 05:51:45 +00006688/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00006689static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6690 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006691 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00006692
6693 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006694 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00006695 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006696
Chris Lattnerebca4762006-04-02 05:37:12 +00006697 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6698 isa<PackedType>(DestPTy)) {
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006699 // If the source is an array, the code below will not succeed. Check to
6700 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6701 // constants.
6702 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6703 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6704 if (ASrcTy->getNumElements() != 0) {
6705 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6706 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6707 SrcTy = cast<PointerType>(CastOp->getType());
6708 SrcPTy = SrcTy->getElementType();
6709 }
6710
Chris Lattnerebca4762006-04-02 05:37:12 +00006711 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6712 isa<PackedType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00006713 // Do not allow turning this into a load of an integer, which is then
6714 // casted to a pointer, this pessimizes pointer analysis a lot.
6715 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006716 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006717 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00006718
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00006719 // Okay, we are casting from one integer or pointer type to another of
6720 // the same size. Instead of casting the pointer before the load, cast
6721 // the result of the loaded value.
6722 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6723 CI->getName(),
6724 LI.isVolatile()),LI);
6725 // Now cast the result of the load.
6726 return new CastInst(NewLoad, LI.getType());
6727 }
Chris Lattner35e24772004-07-13 01:49:43 +00006728 }
6729 }
6730 return 0;
6731}
6732
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006733/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00006734/// from this value cannot trap. If it is not obviously safe to load from the
6735/// specified pointer, we do a quick local scan of the basic block containing
6736/// ScanFrom, to determine if the address is already accessed.
6737static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6738 // If it is an alloca or global variable, it is always safe to load from.
6739 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6740
6741 // Otherwise, be a little bit agressive by scanning the local block where we
6742 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006743 // from/to. If so, the previous load or store would have already trapped,
6744 // so there is no harm doing an extra load (also, CSE will later eliminate
6745 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00006746 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6747
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006748 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00006749 --BBI;
6750
6751 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6752 if (LI->getOperand(0) == V) return true;
6753 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6754 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00006755
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00006756 }
Chris Lattnere6f13092004-09-19 19:18:10 +00006757 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006758}
6759
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006760Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6761 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00006762
Chris Lattnera9d84e32005-05-01 04:24:53 +00006763 // load (cast X) --> cast (load X) iff safe
6764 if (CastInst *CI = dyn_cast<CastInst>(Op))
6765 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6766 return Res;
6767
6768 // None of the following transforms are legal for volatile loads.
6769 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006770
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006771 if (&LI.getParent()->front() != &LI) {
6772 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006773 // If the instruction immediately before this is a store to the same
6774 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006775 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6776 if (SI->getOperand(1) == LI.getOperand(0))
6777 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00006778 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6779 if (LIB->getOperand(0) == LI.getOperand(0))
6780 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00006781 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00006782
6783 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6784 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6785 isa<UndefValue>(GEPI->getOperand(0))) {
6786 // Insert a new store to null instruction before the load to indicate
6787 // that this code is not reachable. We do this instead of inserting
6788 // an unreachable instruction directly because we cannot modify the
6789 // CFG.
6790 new StoreInst(UndefValue::get(LI.getType()),
6791 Constant::getNullValue(Op->getType()), &LI);
6792 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6793 }
6794
Chris Lattner81a7a232004-10-16 18:11:37 +00006795 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00006796 // load null/undef -> undef
6797 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006798 // Insert a new store to null instruction before the load to indicate that
6799 // this code is not reachable. We do this instead of inserting an
6800 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00006801 new StoreInst(UndefValue::get(LI.getType()),
6802 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00006803 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00006804 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006805
Chris Lattner81a7a232004-10-16 18:11:37 +00006806 // Instcombine load (constant global) into the value loaded.
6807 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6808 if (GV->isConstant() && !GV->isExternal())
6809 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00006810
Chris Lattner81a7a232004-10-16 18:11:37 +00006811 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6812 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6813 if (CE->getOpcode() == Instruction::GetElementPtr) {
6814 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6815 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00006816 if (Constant *V =
6817 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00006818 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00006819 if (CE->getOperand(0)->isNullValue()) {
6820 // Insert a new store to null instruction before the load to indicate
6821 // that this code is not reachable. We do this instead of inserting
6822 // an unreachable instruction directly because we cannot modify the
6823 // CFG.
6824 new StoreInst(UndefValue::get(LI.getType()),
6825 Constant::getNullValue(Op->getType()), &LI);
6826 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6827 }
6828
Chris Lattner81a7a232004-10-16 18:11:37 +00006829 } else if (CE->getOpcode() == Instruction::Cast) {
6830 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6831 return Res;
6832 }
6833 }
Chris Lattnere228ee52004-04-08 20:39:49 +00006834
Chris Lattnera9d84e32005-05-01 04:24:53 +00006835 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006836 // Change select and PHI nodes to select values instead of addresses: this
6837 // helps alias analysis out a lot, allows many others simplifications, and
6838 // exposes redundancy in the code.
6839 //
6840 // Note that we cannot do the transformation unless we know that the
6841 // introduced loads cannot trap! Something like this is valid as long as
6842 // the condition is always false: load (select bool %C, int* null, int* %G),
6843 // but it would not be valid if we transformed it to load from null
6844 // unconditionally.
6845 //
6846 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6847 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00006848 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6849 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006850 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00006851 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006852 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00006853 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006854 return new SelectInst(SI->getCondition(), V1, V2);
6855 }
6856
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00006857 // load (select (cond, null, P)) -> load P
6858 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6859 if (C->isNullValue()) {
6860 LI.setOperand(0, SI->getOperand(2));
6861 return &LI;
6862 }
6863
6864 // load (select (cond, P, null)) -> load P
6865 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6866 if (C->isNullValue()) {
6867 LI.setOperand(0, SI->getOperand(1));
6868 return &LI;
6869 }
6870
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006871 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6872 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00006873 bool Safe = PN->getParent() == LI.getParent();
6874
6875 // Scan all of the instructions between the PHI and the load to make
6876 // sure there are no instructions that might possibly alter the value
6877 // loaded from the PHI.
6878 if (Safe) {
6879 BasicBlock::iterator I = &LI;
6880 for (--I; !isa<PHINode>(I); --I)
6881 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6882 Safe = false;
6883 break;
6884 }
6885 }
6886
6887 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00006888 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00006889 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006890 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00006891
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00006892 if (Safe) {
6893 // Create the PHI.
6894 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6895 InsertNewInstBefore(NewPN, *PN);
6896 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6897
6898 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6899 BasicBlock *BB = PN->getIncomingBlock(i);
6900 Value *&TheLoad = LoadMap[BB];
6901 if (TheLoad == 0) {
6902 Value *InVal = PN->getIncomingValue(i);
6903 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6904 InVal->getName()+".val"),
6905 *BB->getTerminator());
6906 }
6907 NewPN->addIncoming(TheLoad, BB);
6908 }
6909 return ReplaceInstUsesWith(LI, NewPN);
6910 }
6911 }
6912 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00006913 return 0;
6914}
6915
Chris Lattner72684fe2005-01-31 05:51:45 +00006916/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6917/// when possible.
6918static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6919 User *CI = cast<User>(SI.getOperand(1));
6920 Value *CastOp = CI->getOperand(0);
6921
6922 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6923 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6924 const Type *SrcPTy = SrcTy->getElementType();
6925
6926 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6927 // If the source is an array, the code below will not succeed. Check to
6928 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6929 // constants.
6930 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6931 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6932 if (ASrcTy->getNumElements() != 0) {
6933 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6934 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6935 SrcTy = cast<PointerType>(CastOp->getType());
6936 SrcPTy = SrcTy->getElementType();
6937 }
6938
6939 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00006940 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00006941 IC.getTargetData().getTypeSize(DestPTy)) {
6942
6943 // Okay, we are casting from one integer or pointer type to another of
6944 // the same size. Instead of casting the pointer before the store, cast
6945 // the value to be stored.
6946 Value *NewCast;
6947 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6948 NewCast = ConstantExpr::getCast(C, SrcPTy);
6949 else
6950 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6951 SrcPTy,
6952 SI.getOperand(0)->getName()+".c"), SI);
6953
6954 return new StoreInst(NewCast, CastOp);
6955 }
6956 }
6957 }
6958 return 0;
6959}
6960
Chris Lattner31f486c2005-01-31 05:36:43 +00006961Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6962 Value *Val = SI.getOperand(0);
6963 Value *Ptr = SI.getOperand(1);
6964
6965 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner5997cf92006-02-08 03:25:32 +00006966 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00006967 ++NumCombined;
6968 return 0;
6969 }
6970
Chris Lattner5997cf92006-02-08 03:25:32 +00006971 // Do really simple DSE, to catch cases where there are several consequtive
6972 // stores to the same location, separated by a few arithmetic operations. This
6973 // situation often occurs with bitfield accesses.
6974 BasicBlock::iterator BBI = &SI;
6975 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6976 --ScanInsts) {
6977 --BBI;
6978
6979 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6980 // Prev store isn't volatile, and stores to the same location?
6981 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6982 ++NumDeadStore;
6983 ++BBI;
6984 EraseInstFromFunction(*PrevSI);
6985 continue;
6986 }
6987 break;
6988 }
6989
Chris Lattnerdab43b22006-05-26 19:19:20 +00006990 // If this is a load, we have to stop. However, if the loaded value is from
6991 // the pointer we're loading and is producing the pointer we're storing,
6992 // then *this* store is dead (X = load P; store X -> P).
6993 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6994 if (LI == Val && LI->getOperand(0) == Ptr) {
6995 EraseInstFromFunction(SI);
6996 ++NumCombined;
6997 return 0;
6998 }
6999 // Otherwise, this is a load from some other location. Stores before it
7000 // may not be dead.
7001 break;
7002 }
7003
Chris Lattner5997cf92006-02-08 03:25:32 +00007004 // Don't skip over loads or things that can modify memory.
Chris Lattnerdab43b22006-05-26 19:19:20 +00007005 if (BBI->mayWriteToMemory())
Chris Lattner5997cf92006-02-08 03:25:32 +00007006 break;
7007 }
7008
7009
7010 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner31f486c2005-01-31 05:36:43 +00007011
7012 // store X, null -> turns into 'unreachable' in SimplifyCFG
7013 if (isa<ConstantPointerNull>(Ptr)) {
7014 if (!isa<UndefValue>(Val)) {
7015 SI.setOperand(0, UndefValue::get(Val->getType()));
7016 if (Instruction *U = dyn_cast<Instruction>(Val))
7017 WorkList.push_back(U); // Dropped a use.
7018 ++NumCombined;
7019 }
7020 return 0; // Do not modify these!
7021 }
7022
7023 // store undef, Ptr -> noop
7024 if (isa<UndefValue>(Val)) {
Chris Lattner5997cf92006-02-08 03:25:32 +00007025 EraseInstFromFunction(SI);
Chris Lattner31f486c2005-01-31 05:36:43 +00007026 ++NumCombined;
7027 return 0;
7028 }
7029
Chris Lattner72684fe2005-01-31 05:51:45 +00007030 // If the pointer destination is a cast, see if we can fold the cast into the
7031 // source instead.
7032 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7033 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7034 return Res;
7035 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7036 if (CE->getOpcode() == Instruction::Cast)
7037 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7038 return Res;
7039
Chris Lattner219175c2005-09-12 23:23:25 +00007040
7041 // If this store is the last instruction in the basic block, and if the block
7042 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner5997cf92006-02-08 03:25:32 +00007043 BBI = &SI; ++BBI;
Chris Lattner219175c2005-09-12 23:23:25 +00007044 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7045 if (BI->isUnconditional()) {
7046 // Check to see if the successor block has exactly two incoming edges. If
7047 // so, see if the other predecessor contains a store to the same location.
7048 // if so, insert a PHI node (if needed) and move the stores down.
7049 BasicBlock *Dest = BI->getSuccessor(0);
7050
7051 pred_iterator PI = pred_begin(Dest);
7052 BasicBlock *Other = 0;
7053 if (*PI != BI->getParent())
7054 Other = *PI;
7055 ++PI;
7056 if (PI != pred_end(Dest)) {
7057 if (*PI != BI->getParent())
7058 if (Other)
7059 Other = 0;
7060 else
7061 Other = *PI;
7062 if (++PI != pred_end(Dest))
7063 Other = 0;
7064 }
7065 if (Other) { // If only one other pred...
7066 BBI = Other->getTerminator();
7067 // Make sure this other block ends in an unconditional branch and that
7068 // there is an instruction before the branch.
7069 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7070 BBI != Other->begin()) {
7071 --BBI;
7072 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7073
7074 // If this instruction is a store to the same location.
7075 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7076 // Okay, we know we can perform this transformation. Insert a PHI
7077 // node now if we need it.
7078 Value *MergedVal = OtherStore->getOperand(0);
7079 if (MergedVal != SI.getOperand(0)) {
7080 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7081 PN->reserveOperandSpace(2);
7082 PN->addIncoming(SI.getOperand(0), SI.getParent());
7083 PN->addIncoming(OtherStore->getOperand(0), Other);
7084 MergedVal = InsertNewInstBefore(PN, Dest->front());
7085 }
7086
7087 // Advance to a place where it is safe to insert the new store and
7088 // insert it.
7089 BBI = Dest->begin();
7090 while (isa<PHINode>(BBI)) ++BBI;
7091 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7092 OtherStore->isVolatile()), *BBI);
7093
7094 // Nuke the old stores.
Chris Lattner5997cf92006-02-08 03:25:32 +00007095 EraseInstFromFunction(SI);
7096 EraseInstFromFunction(*OtherStore);
Chris Lattner219175c2005-09-12 23:23:25 +00007097 ++NumCombined;
7098 return 0;
7099 }
7100 }
7101 }
7102 }
7103
Chris Lattner31f486c2005-01-31 05:36:43 +00007104 return 0;
7105}
7106
7107
Chris Lattner9eef8a72003-06-04 04:46:00 +00007108Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7109 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00007110 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00007111 BasicBlock *TrueDest;
7112 BasicBlock *FalseDest;
7113 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7114 !isa<Constant>(X)) {
7115 // Swap Destinations and condition...
7116 BI.setCondition(X);
7117 BI.setSuccessor(0, FalseDest);
7118 BI.setSuccessor(1, TrueDest);
7119 return &BI;
7120 }
7121
7122 // Cannonicalize setne -> seteq
7123 Instruction::BinaryOps Op; Value *Y;
7124 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7125 TrueDest, FalseDest)))
7126 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7127 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7128 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7129 std::string Name = I->getName(); I->setName("");
7130 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7131 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00007132 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00007133 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00007134 BI.setSuccessor(0, FalseDest);
7135 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00007136 removeFromWorkList(I);
7137 I->getParent()->getInstList().erase(I);
7138 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00007139 return &BI;
7140 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00007141
Chris Lattner9eef8a72003-06-04 04:46:00 +00007142 return 0;
7143}
Chris Lattner1085bdf2002-11-04 16:18:53 +00007144
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007145Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7146 Value *Cond = SI.getCondition();
7147 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7148 if (I->getOpcode() == Instruction::Add)
7149 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7150 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7151 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00007152 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00007153 AddRHS));
7154 SI.setOperand(0, I->getOperand(0));
7155 WorkList.push_back(I);
7156 return &SI;
7157 }
7158 }
7159 return 0;
7160}
7161
Chris Lattner6bc98652006-03-05 00:22:33 +00007162/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7163/// is to leave as a vector operation.
7164static bool CheapToScalarize(Value *V, bool isConstant) {
7165 if (isa<ConstantAggregateZero>(V))
7166 return true;
7167 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7168 if (isConstant) return true;
7169 // If all elts are the same, we can extract.
7170 Constant *Op0 = C->getOperand(0);
7171 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7172 if (C->getOperand(i) != Op0)
7173 return false;
7174 return true;
7175 }
7176 Instruction *I = dyn_cast<Instruction>(V);
7177 if (!I) return false;
7178
7179 // Insert element gets simplified to the inserted element or is deleted if
7180 // this is constant idx extract element and its a constant idx insertelt.
7181 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7182 isa<ConstantInt>(I->getOperand(2)))
7183 return true;
7184 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7185 return true;
7186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7187 if (BO->hasOneUse() &&
7188 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7189 CheapToScalarize(BO->getOperand(1), isConstant)))
7190 return true;
7191
7192 return false;
7193}
7194
Chris Lattner12249be2006-05-25 23:48:38 +00007195/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7196/// elements into values that are larger than the #elts in the input.
7197static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7198 unsigned NElts = SVI->getType()->getNumElements();
7199 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7200 return std::vector<unsigned>(NElts, 0);
7201 if (isa<UndefValue>(SVI->getOperand(2)))
7202 return std::vector<unsigned>(NElts, 2*NElts);
7203
7204 std::vector<unsigned> Result;
7205 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7206 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7207 if (isa<UndefValue>(CP->getOperand(i)))
7208 Result.push_back(NElts*2); // undef -> 8
7209 else
7210 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7211 return Result;
7212}
7213
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007214/// FindScalarElement - Given a vector and an element number, see if the scalar
7215/// value is already around as a register, for example if it were inserted then
7216/// extracted from the vector.
7217static Value *FindScalarElement(Value *V, unsigned EltNo) {
7218 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7219 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner2d37f922006-04-10 23:06:36 +00007220 unsigned Width = PTy->getNumElements();
7221 if (EltNo >= Width) // Out of range access.
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007222 return UndefValue::get(PTy->getElementType());
7223
7224 if (isa<UndefValue>(V))
7225 return UndefValue::get(PTy->getElementType());
7226 else if (isa<ConstantAggregateZero>(V))
7227 return Constant::getNullValue(PTy->getElementType());
7228 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7229 return CP->getOperand(EltNo);
7230 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7231 // If this is an insert to a variable element, we don't know what it is.
7232 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7233 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7234
7235 // If this is an insert to the element we are looking for, return the
7236 // inserted value.
7237 if (EltNo == IIElt) return III->getOperand(1);
7238
7239 // Otherwise, the insertelement doesn't modify the value, recurse on its
7240 // vector input.
7241 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner2d37f922006-04-10 23:06:36 +00007242 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner12249be2006-05-25 23:48:38 +00007243 unsigned InEl = getShuffleMask(SVI)[EltNo];
7244 if (InEl < Width)
7245 return FindScalarElement(SVI->getOperand(0), InEl);
7246 else if (InEl < Width*2)
7247 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7248 else
7249 return UndefValue::get(PTy->getElementType());
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007250 }
7251
7252 // Otherwise, we don't know.
7253 return 0;
7254}
7255
Robert Bocchinoa8352962006-01-13 22:48:06 +00007256Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007257
Chris Lattner92346c32006-03-31 18:25:14 +00007258 // If packed val is undef, replace extract with scalar undef.
7259 if (isa<UndefValue>(EI.getOperand(0)))
7260 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7261
7262 // If packed val is constant 0, replace extract with scalar 0.
7263 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7264 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7265
Robert Bocchinoa8352962006-01-13 22:48:06 +00007266 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7267 // If packed val is constant with uniform operands, replace EI
7268 // with that operand
Chris Lattner6bc98652006-03-05 00:22:33 +00007269 Constant *op0 = C->getOperand(0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007270 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner6bc98652006-03-05 00:22:33 +00007271 if (C->getOperand(i) != op0) {
7272 op0 = 0;
7273 break;
7274 }
7275 if (op0)
7276 return ReplaceInstUsesWith(EI, op0);
Robert Bocchinoa8352962006-01-13 22:48:06 +00007277 }
Chris Lattner6bc98652006-03-05 00:22:33 +00007278
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007279 // If extracting a specified index from the vector, see if we can recursively
7280 // find a previously computed scalar that was inserted into the vector.
Chris Lattner2d37f922006-04-10 23:06:36 +00007281 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007282 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7283 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner2d37f922006-04-10 23:06:36 +00007284 }
Chris Lattner8d1d8d32006-03-31 23:01:56 +00007285
Chris Lattner83f65782006-05-25 22:53:38 +00007286 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007287 if (I->hasOneUse()) {
7288 // Push extractelement into predecessor operation if legal and
7289 // profitable to do so
7290 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner6bc98652006-03-05 00:22:33 +00007291 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7292 if (CheapToScalarize(BO, isConstantElt)) {
7293 ExtractElementInst *newEI0 =
7294 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7295 EI.getName()+".lhs");
7296 ExtractElementInst *newEI1 =
7297 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7298 EI.getName()+".rhs");
7299 InsertNewInstBefore(newEI0, EI);
7300 InsertNewInstBefore(newEI1, EI);
7301 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7302 }
7303 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchinoa8352962006-01-13 22:48:06 +00007304 Value *Ptr = InsertCastBefore(I->getOperand(0),
7305 PointerType::get(EI.getType()), EI);
7306 GetElementPtrInst *GEP =
7307 new GetElementPtrInst(Ptr, EI.getOperand(1),
7308 I->getName() + ".gep");
7309 InsertNewInstBefore(GEP, EI);
7310 return new LoadInst(GEP);
Chris Lattner83f65782006-05-25 22:53:38 +00007311 }
7312 }
7313 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7314 // Extracting the inserted element?
7315 if (IE->getOperand(2) == EI.getOperand(1))
7316 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7317 // If the inserted and extracted elements are constants, they must not
7318 // be the same value, extract from the pre-inserted value instead.
7319 if (isa<Constant>(IE->getOperand(2)) &&
7320 isa<Constant>(EI.getOperand(1))) {
7321 AddUsesToWorkList(EI);
7322 EI.setOperand(0, IE->getOperand(0));
7323 return &EI;
7324 }
7325 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7326 // If this is extracting an element from a shufflevector, figure out where
7327 // it came from and extract from the appropriate input element instead.
7328 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner12249be2006-05-25 23:48:38 +00007329 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7330 Value *Src;
7331 if (SrcIdx < SVI->getType()->getNumElements())
7332 Src = SVI->getOperand(0);
7333 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7334 SrcIdx -= SVI->getType()->getNumElements();
7335 Src = SVI->getOperand(1);
7336 } else {
7337 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner612fa8e2006-03-30 22:02:40 +00007338 }
Chris Lattner12249be2006-05-25 23:48:38 +00007339 return new ExtractElementInst(Src,
7340 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchinoa8352962006-01-13 22:48:06 +00007341 }
7342 }
Chris Lattner83f65782006-05-25 22:53:38 +00007343 }
Robert Bocchinoa8352962006-01-13 22:48:06 +00007344 return 0;
7345}
7346
Chris Lattner90951862006-04-16 00:51:47 +00007347/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7348/// elements from either LHS or RHS, return the shuffle mask and true.
7349/// Otherwise, return false.
7350static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7351 std::vector<Constant*> &Mask) {
7352 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7353 "Invalid CollectSingleShuffleElements");
7354 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7355
7356 if (isa<UndefValue>(V)) {
7357 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7358 return true;
7359 } else if (V == LHS) {
7360 for (unsigned i = 0; i != NumElts; ++i)
7361 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7362 return true;
7363 } else if (V == RHS) {
7364 for (unsigned i = 0; i != NumElts; ++i)
7365 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7366 return true;
7367 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7368 // If this is an insert of an extract from some other vector, include it.
7369 Value *VecOp = IEI->getOperand(0);
7370 Value *ScalarOp = IEI->getOperand(1);
7371 Value *IdxOp = IEI->getOperand(2);
7372
Chris Lattnerb6cb64b2006-04-27 21:14:21 +00007373 if (!isa<ConstantInt>(IdxOp))
7374 return false;
7375 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7376
7377 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7378 // Okay, we can handle this if the vector we are insertinting into is
7379 // transitively ok.
7380 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7381 // If so, update the mask to reflect the inserted undef.
7382 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7383 return true;
7384 }
7385 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7386 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner90951862006-04-16 00:51:47 +00007387 EI->getOperand(0)->getType() == V->getType()) {
7388 unsigned ExtractedIdx =
7389 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner90951862006-04-16 00:51:47 +00007390
7391 // This must be extracting from either LHS or RHS.
7392 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7393 // Okay, we can handle this if the vector we are insertinting into is
7394 // transitively ok.
7395 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7396 // If so, update the mask to reflect the inserted value.
7397 if (EI->getOperand(0) == LHS) {
7398 Mask[InsertedIdx & (NumElts-1)] =
7399 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7400 } else {
7401 assert(EI->getOperand(0) == RHS);
7402 Mask[InsertedIdx & (NumElts-1)] =
7403 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7404
7405 }
7406 return true;
7407 }
7408 }
7409 }
7410 }
7411 }
7412 // TODO: Handle shufflevector here!
7413
7414 return false;
7415}
7416
7417/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7418/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7419/// that computes V and the LHS value of the shuffle.
Chris Lattner39fac442006-04-15 01:39:45 +00007420static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner90951862006-04-16 00:51:47 +00007421 Value *&RHS) {
7422 assert(isa<PackedType>(V->getType()) &&
7423 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattner39fac442006-04-15 01:39:45 +00007424 "Invalid shuffle!");
7425 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7426
7427 if (isa<UndefValue>(V)) {
7428 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7429 return V;
7430 } else if (isa<ConstantAggregateZero>(V)) {
7431 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7432 return V;
7433 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7434 // If this is an insert of an extract from some other vector, include it.
7435 Value *VecOp = IEI->getOperand(0);
7436 Value *ScalarOp = IEI->getOperand(1);
7437 Value *IdxOp = IEI->getOperand(2);
7438
7439 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7440 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7441 EI->getOperand(0)->getType() == V->getType()) {
7442 unsigned ExtractedIdx =
7443 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7444 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7445
7446 // Either the extracted from or inserted into vector must be RHSVec,
7447 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner90951862006-04-16 00:51:47 +00007448 if (EI->getOperand(0) == RHS || RHS == 0) {
7449 RHS = EI->getOperand(0);
7450 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007451 Mask[InsertedIdx & (NumElts-1)] =
7452 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7453 return V;
7454 }
7455
Chris Lattner90951862006-04-16 00:51:47 +00007456 if (VecOp == RHS) {
7457 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattner39fac442006-04-15 01:39:45 +00007458 // Everything but the extracted element is replaced with the RHS.
7459 for (unsigned i = 0; i != NumElts; ++i) {
7460 if (i != InsertedIdx)
7461 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7462 }
7463 return V;
7464 }
Chris Lattner90951862006-04-16 00:51:47 +00007465
7466 // If this insertelement is a chain that comes from exactly these two
7467 // vectors, return the vector and the effective shuffle.
7468 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7469 return EI->getOperand(0);
7470
Chris Lattner39fac442006-04-15 01:39:45 +00007471 }
7472 }
7473 }
Chris Lattner90951862006-04-16 00:51:47 +00007474 // TODO: Handle shufflevector here!
Chris Lattner39fac442006-04-15 01:39:45 +00007475
7476 // Otherwise, can't do anything fancy. Return an identity vector.
7477 for (unsigned i = 0; i != NumElts; ++i)
7478 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7479 return V;
7480}
7481
7482Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7483 Value *VecOp = IE.getOperand(0);
7484 Value *ScalarOp = IE.getOperand(1);
7485 Value *IdxOp = IE.getOperand(2);
7486
7487 // If the inserted element was extracted from some other vector, and if the
7488 // indexes are constant, try to turn this into a shufflevector operation.
7489 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7490 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7491 EI->getOperand(0)->getType() == IE.getType()) {
7492 unsigned NumVectorElts = IE.getType()->getNumElements();
7493 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7494 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7495
7496 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7497 return ReplaceInstUsesWith(IE, VecOp);
7498
7499 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7500 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7501
7502 // If we are extracting a value from a vector, then inserting it right
7503 // back into the same place, just use the input vector.
7504 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7505 return ReplaceInstUsesWith(IE, VecOp);
7506
7507 // We could theoretically do this for ANY input. However, doing so could
7508 // turn chains of insertelement instructions into a chain of shufflevector
7509 // instructions, and right now we do not merge shufflevectors. As such,
7510 // only do this in a situation where it is clear that there is benefit.
7511 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7512 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7513 // the values of VecOp, except then one read from EIOp0.
7514 // Build a new shuffle mask.
7515 std::vector<Constant*> Mask;
7516 if (isa<UndefValue>(VecOp))
7517 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7518 else {
7519 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7520 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7521 NumVectorElts));
7522 }
7523 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7524 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7525 ConstantPacked::get(Mask));
7526 }
7527
7528 // If this insertelement isn't used by some other insertelement, turn it
7529 // (and any insertelements it points to), into one big shuffle.
7530 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7531 std::vector<Constant*> Mask;
Chris Lattner90951862006-04-16 00:51:47 +00007532 Value *RHS = 0;
7533 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7534 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7535 // We now have a shuffle of LHS, RHS, Mask.
7536 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattner39fac442006-04-15 01:39:45 +00007537 }
7538 }
7539 }
7540
7541 return 0;
7542}
7543
7544
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007545Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7546 Value *LHS = SVI.getOperand(0);
7547 Value *RHS = SVI.getOperand(1);
Chris Lattner12249be2006-05-25 23:48:38 +00007548 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007549
7550 bool MadeChange = false;
7551
Chris Lattner12249be2006-05-25 23:48:38 +00007552 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007553 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7554
Chris Lattner39fac442006-04-15 01:39:45 +00007555 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7556 // the undef, change them to undefs.
7557
Chris Lattner12249be2006-05-25 23:48:38 +00007558 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7559 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7560 if (LHS == RHS || isa<UndefValue>(LHS)) {
7561 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007562 // shuffle(undef,undef,mask) -> undef.
7563 return ReplaceInstUsesWith(SVI, LHS);
7564 }
7565
Chris Lattner12249be2006-05-25 23:48:38 +00007566 // Remap any references to RHS to use LHS.
7567 std::vector<Constant*> Elts;
7568 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner0e477162006-05-26 00:29:06 +00007569 if (Mask[i] >= 2*e)
Chris Lattner12249be2006-05-25 23:48:38 +00007570 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner0e477162006-05-26 00:29:06 +00007571 else {
7572 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7573 (Mask[i] < e && isa<UndefValue>(LHS)))
7574 Mask[i] = 2*e; // Turn into undef.
7575 else
7576 Mask[i] &= (e-1); // Force to LHS.
7577 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7578 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007579 }
Chris Lattner12249be2006-05-25 23:48:38 +00007580 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007581 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner12249be2006-05-25 23:48:38 +00007582 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner0e477162006-05-26 00:29:06 +00007583 LHS = SVI.getOperand(0);
7584 RHS = SVI.getOperand(1);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007585 MadeChange = true;
7586 }
7587
Chris Lattner0e477162006-05-26 00:29:06 +00007588 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner12249be2006-05-25 23:48:38 +00007589 bool isLHSID = true, isRHSID = true;
Chris Lattner34cebe72006-04-16 00:03:56 +00007590
Chris Lattner12249be2006-05-25 23:48:38 +00007591 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7592 if (Mask[i] >= e*2) continue; // Ignore undef values.
7593 // Is this an identity shuffle of the LHS value?
7594 isLHSID &= (Mask[i] == i);
7595
7596 // Is this an identity shuffle of the RHS value?
7597 isRHSID &= (Mask[i]-e == i);
Chris Lattner34cebe72006-04-16 00:03:56 +00007598 }
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007599
Chris Lattner12249be2006-05-25 23:48:38 +00007600 // Eliminate identity shuffles.
7601 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7602 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007603
Chris Lattner0e477162006-05-26 00:29:06 +00007604 // If the LHS is a shufflevector itself, see if we can combine it with this
7605 // one without producing an unusual shuffle. Here we are really conservative:
7606 // we are absolutely afraid of producing a shuffle mask not in the input
7607 // program, because the code gen may not be smart enough to turn a merged
7608 // shuffle into two specific shuffles: it may produce worse code. As such,
7609 // we only merge two shuffles if the result is one of the two input shuffle
7610 // masks. In this case, merging the shuffles just removes one instruction,
7611 // which we know is safe. This is good for things like turning:
7612 // (splat(splat)) -> splat.
7613 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7614 if (isa<UndefValue>(RHS)) {
7615 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7616
7617 std::vector<unsigned> NewMask;
7618 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7619 if (Mask[i] >= 2*e)
7620 NewMask.push_back(2*e);
7621 else
7622 NewMask.push_back(LHSMask[Mask[i]]);
7623
7624 // If the result mask is equal to the src shuffle or this shuffle mask, do
7625 // the replacement.
7626 if (NewMask == LHSMask || NewMask == Mask) {
7627 std::vector<Constant*> Elts;
7628 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7629 if (NewMask[i] >= e*2) {
7630 Elts.push_back(UndefValue::get(Type::UIntTy));
7631 } else {
7632 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7633 }
7634 }
7635 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7636 LHSSVI->getOperand(1),
7637 ConstantPacked::get(Elts));
7638 }
7639 }
7640 }
7641
Chris Lattnerfbb77a42006-04-10 22:45:52 +00007642 return MadeChange ? &SVI : 0;
7643}
7644
7645
Robert Bocchinoa8352962006-01-13 22:48:06 +00007646
Chris Lattner99f48c62002-09-02 04:59:56 +00007647void InstCombiner::removeFromWorkList(Instruction *I) {
7648 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7649 WorkList.end());
7650}
7651
Chris Lattner39c98bb2004-12-08 23:43:58 +00007652
7653/// TryToSinkInstruction - Try to move the specified instruction from its
7654/// current block into the beginning of DestBlock, which can only happen if it's
7655/// safe to move the instruction past all of the instructions between it and the
7656/// end of its block.
7657static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7658 assert(I->hasOneUse() && "Invariants didn't hold!");
7659
Chris Lattnerc4f67e62005-10-27 17:13:11 +00007660 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7661 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00007662
Chris Lattner39c98bb2004-12-08 23:43:58 +00007663 // Do not sink alloca instructions out of the entry block.
7664 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7665 return false;
7666
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007667 // We can only sink load instructions if there is nothing between the load and
7668 // the end of block that could change the value.
7669 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007670 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7671 Scan != E; ++Scan)
7672 if (Scan->mayWriteToMemory())
7673 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00007674 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00007675
7676 BasicBlock::iterator InsertPos = DestBlock->begin();
7677 while (isa<PHINode>(InsertPos)) ++InsertPos;
7678
Chris Lattner9f269e42005-08-08 19:11:57 +00007679 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00007680 ++NumSunkInst;
7681 return true;
7682}
7683
Chris Lattner1443bc52006-05-11 17:11:52 +00007684/// OptimizeConstantExpr - Given a constant expression and target data layout
7685/// information, symbolically evaluation the constant expr to something simpler
7686/// if possible.
7687static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7688 if (!TD) return CE;
7689
7690 Constant *Ptr = CE->getOperand(0);
7691 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7692 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7693 // If this is a constant expr gep that is effectively computing an
7694 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7695 bool isFoldableGEP = true;
7696 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7697 if (!isa<ConstantInt>(CE->getOperand(i)))
7698 isFoldableGEP = false;
7699 if (isFoldableGEP) {
7700 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7701 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7702 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7703 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7704 return ConstantExpr::getCast(C, CE->getType());
7705 }
7706 }
7707
7708 return CE;
7709}
7710
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007711
7712/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7713/// all reachable code to the worklist.
7714///
7715/// This has a couple of tricks to make the code faster and more powerful. In
7716/// particular, we constant fold and DCE instructions as we go, to avoid adding
7717/// them to the worklist (this significantly speeds up instcombine on code where
7718/// many instructions are dead or constant). Additionally, if we find a branch
7719/// whose condition is a known constant, we only visit the reachable successors.
7720///
7721static void AddReachableCodeToWorklist(BasicBlock *BB,
7722 std::set<BasicBlock*> &Visited,
Chris Lattner1443bc52006-05-11 17:11:52 +00007723 std::vector<Instruction*> &WorkList,
7724 const TargetData *TD) {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007725 // We have now visited this block! If we've already been here, bail out.
7726 if (!Visited.insert(BB).second) return;
7727
7728 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7729 Instruction *Inst = BBI++;
7730
7731 // DCE instruction if trivially dead.
7732 if (isInstructionTriviallyDead(Inst)) {
7733 ++NumDeadInst;
7734 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7735 Inst->eraseFromParent();
7736 continue;
7737 }
7738
7739 // ConstantProp instruction if trivially constant.
7740 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007741 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7742 C = OptimizeConstantExpr(CE, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007743 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7744 Inst->replaceAllUsesWith(C);
7745 ++NumConstProp;
7746 Inst->eraseFromParent();
7747 continue;
7748 }
7749
7750 WorkList.push_back(Inst);
7751 }
7752
7753 // Recursively visit successors. If this is a branch or switch on a constant,
7754 // only visit the reachable successor.
7755 TerminatorInst *TI = BB->getTerminator();
7756 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7757 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7758 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner1443bc52006-05-11 17:11:52 +00007759 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7760 TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007761 return;
7762 }
7763 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7764 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7765 // See if this is an explicit destination.
7766 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7767 if (SI->getCaseValue(i) == Cond) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007768 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007769 return;
7770 }
7771
7772 // Otherwise it is the default destination.
Chris Lattner1443bc52006-05-11 17:11:52 +00007773 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007774 return;
7775 }
7776 }
7777
7778 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner1443bc52006-05-11 17:11:52 +00007779 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007780}
7781
Chris Lattner113f4f42002-06-25 16:13:24 +00007782bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00007783 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00007784 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00007785
Chris Lattner4ed40f72005-07-07 20:40:38 +00007786 {
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007787 // Do a depth-first traversal of the function, populate the worklist with
7788 // the reachable instructions. Ignore blocks that are not reachable. Keep
7789 // track of which blocks we visit.
Chris Lattner4ed40f72005-07-07 20:40:38 +00007790 std::set<BasicBlock*> Visited;
Chris Lattner1443bc52006-05-11 17:11:52 +00007791 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00007792
Chris Lattner4ed40f72005-07-07 20:40:38 +00007793 // Do a quick scan over the function. If we find any blocks that are
7794 // unreachable, remove any instructions inside of them. This prevents
7795 // the instcombine code from having to deal with some bad special cases.
7796 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7797 if (!Visited.count(BB)) {
7798 Instruction *Term = BB->getTerminator();
7799 while (Term != BB->begin()) { // Remove instrs bottom-up
7800 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00007801
Chris Lattner4ed40f72005-07-07 20:40:38 +00007802 DEBUG(std::cerr << "IC: DCE: " << *I);
7803 ++NumDeadInst;
7804
7805 if (!I->use_empty())
7806 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7807 I->eraseFromParent();
7808 }
7809 }
7810 }
Chris Lattnerca081252001-12-14 16:52:21 +00007811
7812 while (!WorkList.empty()) {
7813 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7814 WorkList.pop_back();
7815
Chris Lattner1443bc52006-05-11 17:11:52 +00007816 // Check to see if we can DCE the instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007817 if (isInstructionTriviallyDead(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007818 // Add operands to the worklist.
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007819 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00007820 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00007821 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007822
Chris Lattnercd517ff2005-01-28 19:32:01 +00007823 DEBUG(std::cerr << "IC: DCE: " << *I);
7824
7825 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007826 removeFromWorkList(I);
7827 continue;
7828 }
Chris Lattner99f48c62002-09-02 04:59:56 +00007829
Chris Lattner1443bc52006-05-11 17:11:52 +00007830 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner99f48c62002-09-02 04:59:56 +00007831 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner1443bc52006-05-11 17:11:52 +00007832 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7833 C = OptimizeConstantExpr(CE, TD);
Chris Lattnercd517ff2005-01-28 19:32:01 +00007834 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7835
Chris Lattner1443bc52006-05-11 17:11:52 +00007836 // Add operands to the worklist.
Chris Lattner51ea1272004-02-28 05:22:00 +00007837 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00007838 ReplaceInstUsesWith(*I, C);
7839
Chris Lattner99f48c62002-09-02 04:59:56 +00007840 ++NumConstProp;
Chris Lattnera36ee4e2006-05-10 19:00:36 +00007841 I->eraseFromParent();
Chris Lattner800aaaf2003-10-07 15:17:02 +00007842 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007843 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00007844 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007845
Chris Lattner39c98bb2004-12-08 23:43:58 +00007846 // See if we can trivially sink this instruction to a successor basic block.
7847 if (I->hasOneUse()) {
7848 BasicBlock *BB = I->getParent();
7849 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7850 if (UserParent != BB) {
7851 bool UserIsSuccessor = false;
7852 // See if the user is one of our successors.
7853 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7854 if (*SI == UserParent) {
7855 UserIsSuccessor = true;
7856 break;
7857 }
7858
7859 // If the user is one of our immediate successors, and if that successor
7860 // only has us as a predecessors (we'd have to split the critical edge
7861 // otherwise), we can keep going.
7862 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7863 next(pred_begin(UserParent)) == pred_end(UserParent))
7864 // Okay, the CFG is simple enough, try to sink this instruction.
7865 Changed |= TryToSinkInstruction(I, UserParent);
7866 }
7867 }
7868
Chris Lattnerca081252001-12-14 16:52:21 +00007869 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007870 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00007871 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00007872 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00007873 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007874 DEBUG(std::cerr << "IC: Old = " << *I
7875 << " New = " << *Result);
7876
Chris Lattner396dbfe2004-06-09 05:08:07 +00007877 // Everything uses the new instruction now.
7878 I->replaceAllUsesWith(Result);
7879
7880 // Push the new instruction and any users onto the worklist.
7881 WorkList.push_back(Result);
7882 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007883
7884 // Move the name to the new instruction first...
7885 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00007886 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007887
7888 // Insert the new instruction into the basic block...
7889 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00007890 BasicBlock::iterator InsertPos = I;
7891
7892 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7893 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7894 ++InsertPos;
7895
7896 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007897
Chris Lattner63d75af2004-05-01 23:27:23 +00007898 // Make sure that we reprocess all operands now that we reduced their
7899 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00007900 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7901 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7902 WorkList.push_back(OpI);
7903
Chris Lattner396dbfe2004-06-09 05:08:07 +00007904 // Instructions can end up on the worklist more than once. Make sure
7905 // we do not process an instruction that has been deleted.
7906 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00007907
7908 // Erase the old instruction.
7909 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00007910 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00007911 DEBUG(std::cerr << "IC: MOD = " << *I);
7912
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007913 // If the instruction was modified, it's possible that it is now dead.
7914 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00007915 if (isInstructionTriviallyDead(I)) {
7916 // Make sure we process all operands now that we are reducing their
7917 // use counts.
7918 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7919 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7920 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00007921
Chris Lattner63d75af2004-05-01 23:27:23 +00007922 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchinoa8352962006-01-13 22:48:06 +00007923 // occurrences of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00007924 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00007925 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00007926 } else {
7927 WorkList.push_back(Result);
7928 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00007929 }
Chris Lattner053c0932002-05-14 15:24:07 +00007930 }
Chris Lattner260ab202002-04-18 17:39:14 +00007931 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00007932 }
7933 }
7934
Chris Lattner260ab202002-04-18 17:39:14 +00007935 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00007936}
7937
Brian Gaeke38b79e82004-07-27 17:43:21 +00007938FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00007939 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00007940}
Brian Gaeke960707c2003-11-11 22:41:34 +00007941