blob: 223624049eedebfb3e98dc0bae475bce5053bda4 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-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 Lattnerdf17af12003-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 Lattner2cd91962003-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 Lattnere92d2f42003-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 Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-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 Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattnerdd841ae2002-04-18 17:39:14 +000058namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner9ca96412006-02-08 03:25:32 +000062 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000063 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000064
Chris Lattnerf4b54612006-06-28 22:08:15 +000065 class VISIBILITY_HIDDEN InstCombiner
66 : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000071
Chris Lattner7bcc0e72004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner7bcc0e72004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
Chris Lattner867b99f2006-10-05 06:55:50 +000090
91 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92 /// dead. Add all of its operands to the worklist, turning them into
93 /// undef's to reduce the number of uses of those instructions.
94 ///
95 /// Return the specified operand before it is turned into an undef.
96 ///
97 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98 Value *R = I.getOperand(op);
99
100 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102 WorkList.push_back(Op);
103 // Set the operand to undef to drop the use.
104 I.setOperand(i, UndefValue::get(Op->getType()));
105 }
106
107 return R;
108 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000109
Chris Lattner62b14df2002-09-02 04:59:56 +0000110 // removeFromWorkList - remove all instances of I from the worklist.
111 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000112 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000113 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000114
Chris Lattner97e52e42002-04-28 21:27:06 +0000115 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000116 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000117 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000118 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000119 }
120
Chris Lattner28977af2004-04-05 01:30:19 +0000121 TargetData &getTargetData() const { return *TD; }
122
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000123 // Visitation implementation - Implement instruction combining for different
124 // instruction types. The semantics are as follows:
125 // Return Value:
126 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000127 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000128 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000129 //
Chris Lattner7e708292002-06-25 16:13:24 +0000130 Instruction *visitAdd(BinaryOperator &I);
131 Instruction *visitSub(BinaryOperator &I);
132 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000133 Instruction *visitURem(BinaryOperator &I);
134 Instruction *visitSRem(BinaryOperator &I);
135 Instruction *visitFRem(BinaryOperator &I);
136 Instruction *commonRemTransforms(BinaryOperator &I);
137 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000138 Instruction *commonDivTransforms(BinaryOperator &I);
139 Instruction *commonIDivTransforms(BinaryOperator &I);
140 Instruction *visitUDiv(BinaryOperator &I);
141 Instruction *visitSDiv(BinaryOperator &I);
142 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000143 Instruction *visitAnd(BinaryOperator &I);
144 Instruction *visitOr (BinaryOperator &I);
145 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000146 Instruction *visitSetCondInst(SetCondInst &I);
147 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
148
Chris Lattner574da9b2005-01-13 20:14:25 +0000149 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
150 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000151 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000152 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +0000153 ShiftInst &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000154 Instruction *commonCastTransforms(CastInst &CI);
155 Instruction *commonIntCastTransforms(CastInst &CI);
156 Instruction *visitTrunc(CastInst &CI);
157 Instruction *visitZExt(CastInst &CI);
158 Instruction *visitSExt(CastInst &CI);
159 Instruction *visitFPTrunc(CastInst &CI);
160 Instruction *visitFPExt(CastInst &CI);
161 Instruction *visitFPToUI(CastInst &CI);
162 Instruction *visitFPToSI(CastInst &CI);
163 Instruction *visitUIToFP(CastInst &CI);
164 Instruction *visitSIToFP(CastInst &CI);
165 Instruction *visitPtrToInt(CastInst &CI);
166 Instruction *visitIntToPtr(CastInst &CI);
167 Instruction *visitBitCast(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000168 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
169 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000170 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000171 Instruction *visitCallInst(CallInst &CI);
172 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000173 Instruction *visitPHINode(PHINode &PN);
174 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000175 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000176 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000177 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000178 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000179 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000180 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000181 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000182 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000183 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000184
185 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000186 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000187
Chris Lattner9fe38862003-06-19 17:00:31 +0000188 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000189 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000190 bool transformConstExprCastCall(CallSite CS);
191
Chris Lattner28977af2004-04-05 01:30:19 +0000192 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000193 // InsertNewInstBefore - insert an instruction New before instruction Old
194 // in the program. Add the new instruction to the worklist.
195 //
Chris Lattner955f3312004-09-28 21:48:02 +0000196 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000197 assert(New && New->getParent() == 0 &&
198 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000199 BasicBlock *BB = Old.getParent();
200 BB->getInstList().insert(&Old, New); // Insert inst
201 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000202 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000203 }
204
Chris Lattner0c967662004-09-24 15:21:34 +0000205 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
206 /// This also adds the cast to the worklist. Finally, this returns the
207 /// cast.
208 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
209 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000210
Chris Lattnere2ed0572006-04-06 19:19:17 +0000211 if (Constant *CV = dyn_cast<Constant>(V))
212 return ConstantExpr::getCast(CV, Ty);
213
Reid Spencer3da59db2006-11-27 01:05:10 +0000214 Instruction *C = CastInst::createInferredCast(V, Ty, V->getName(), &Pos);
Chris Lattner0c967662004-09-24 15:21:34 +0000215 WorkList.push_back(C);
216 return C;
217 }
218
Chris Lattner8b170942002-08-09 23:47:40 +0000219 // ReplaceInstUsesWith - This method is to be used when an instruction is
220 // found to be dead, replacable with another preexisting expression. Here
221 // we add all uses of I to the worklist, replace all uses of I with the new
222 // value, then return I, so that the inst combiner will know that I was
223 // modified.
224 //
225 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000226 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000227 if (&I != V) {
228 I.replaceAllUsesWith(V);
229 return &I;
230 } else {
231 // If we are replacing the instruction with itself, this must be in a
232 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000233 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000234 return &I;
235 }
Chris Lattner8b170942002-08-09 23:47:40 +0000236 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000237
Chris Lattner6dce1a72006-02-07 06:56:34 +0000238 // UpdateValueUsesWith - This method is to be used when an value is
239 // found to be replacable with another preexisting expression or was
240 // updated. Here we add all uses of I to the worklist, replace all uses of
241 // I with the new value (unless the instruction was just updated), then
242 // return true, so that the inst combiner will know that I was modified.
243 //
244 bool UpdateValueUsesWith(Value *Old, Value *New) {
245 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
246 if (Old != New)
247 Old->replaceAllUsesWith(New);
248 if (Instruction *I = dyn_cast<Instruction>(Old))
249 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000250 if (Instruction *I = dyn_cast<Instruction>(New))
251 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000252 return true;
253 }
254
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000255 // EraseInstFromFunction - When dealing with an instruction that has side
256 // effects or produces a void value, we can't rely on DCE to delete the
257 // instruction. Instead, visit methods should return the value returned by
258 // this function.
259 Instruction *EraseInstFromFunction(Instruction &I) {
260 assert(I.use_empty() && "Cannot erase instruction that is used!");
261 AddUsesToWorkList(I);
262 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000263 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000264 return 0; // Don't do anything with FI
265 }
266
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000267 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000268 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
269 /// InsertBefore instruction. This is specialized a bit to avoid inserting
270 /// casts that are known to not do anything...
271 ///
272 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
273 Instruction *InsertBefore);
274
Chris Lattnerc8802d22003-03-11 00:12:48 +0000275 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000276 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000277 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000278
Chris Lattner255d8912006-02-11 09:31:47 +0000279 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
280 uint64_t &KnownZero, uint64_t &KnownOne,
281 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000282
Chris Lattner867b99f2006-10-05 06:55:50 +0000283 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
284 uint64_t &UndefElts, unsigned Depth = 0);
285
Chris Lattner4e998b22004-09-29 05:07:12 +0000286 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
287 // PHI node as operand #0, see if we can fold the instruction into the PHI
288 // (which is only possible if all operands to the PHI are constants).
289 Instruction *FoldOpIntoPhi(Instruction &I);
290
Chris Lattnerbac32862004-11-14 19:13:23 +0000291 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
292 // operator and they all are only used by the PHI, PHI together their
293 // inputs, and do the operation once, to the result of the PHI.
294 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000295 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
296
297
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000298 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
299 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000300
301 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
302 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000303 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
304 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000305 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000306 Instruction *MatchBSwap(BinaryOperator &I);
307
Chris Lattner70074e02006-05-13 02:06:03 +0000308 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000309 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000310
Chris Lattner7f8897f2006-08-27 22:42:52 +0000311 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000312}
313
Chris Lattner4f98c562003-03-10 21:43:22 +0000314// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000315// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000316static unsigned getComplexity(Value *V) {
317 if (isa<Instruction>(V)) {
318 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000319 return 3;
320 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000321 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000322 if (isa<Argument>(V)) return 3;
323 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000324}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000325
Chris Lattnerc8802d22003-03-11 00:12:48 +0000326// isOnlyUse - Return true if this instruction will be deleted if we stop using
327// it.
328static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000329 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000330}
331
Chris Lattner4cb170c2004-02-23 06:38:22 +0000332// getPromotedType - Return the specified type promoted as it would be to pass
333// though a va_arg area...
334static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000335 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000336 case Type::SByteTyID:
337 case Type::ShortTyID: return Type::IntTy;
338 case Type::UByteTyID:
339 case Type::UShortTyID: return Type::UIntTy;
340 case Type::FloatTyID: return Type::DoubleTy;
341 default: return Ty;
342 }
343}
344
Reid Spencer3da59db2006-11-27 01:05:10 +0000345/// getBitCastOperand - If the specified operand is a CastInst or a constant
346/// expression bitcast, return the operand value, otherwise return null.
347static Value *getBitCastOperand(Value *V) {
348 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000349 return I->getOperand(0);
350 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000351 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000352 return CE->getOperand(0);
353 return 0;
354}
355
Reid Spencer3da59db2006-11-27 01:05:10 +0000356/// This function is a wrapper around CastInst::isEliminableCastPair. It
357/// simply extracts arguments and returns what that function returns.
358/// @Determine if it is valid to eliminate a Convert pair
359static Instruction::CastOps
360isEliminableCastPair(
361 const CastInst *CI, ///< The first cast instruction
362 unsigned opcode, ///< The opcode of the second cast instruction
363 const Type *DstTy, ///< The target type for the second cast instruction
364 TargetData *TD ///< The target data for pointer size
365) {
366
367 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
368 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000369
Reid Spencer3da59db2006-11-27 01:05:10 +0000370 // Get the opcodes of the two Cast instructions
371 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
372 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000373
Reid Spencer3da59db2006-11-27 01:05:10 +0000374 return Instruction::CastOps(
375 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
376 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000377}
378
379/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
380/// in any code being generated. It does not require codegen if V is simple
381/// enough or if the cast can be folded into other casts.
382static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
383 if (V->getType() == Ty || isa<Constant>(V)) return false;
384
385 // If this is a noop cast, it isn't real codegen.
Reid Spencer3da59db2006-11-27 01:05:10 +0000386 if (V->getType()->canLosslesslyBitCastTo(Ty))
Chris Lattner33a61132006-05-06 09:00:16 +0000387 return false;
388
Chris Lattner01575b72006-05-25 23:24:33 +0000389 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000390 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000391 if (isEliminableCastPair(CI, CastInst::getCastOpcode(V, Ty), Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000392 return false;
393 return true;
394}
395
396/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
397/// InsertBefore instruction. This is specialized a bit to avoid inserting
398/// casts that are known to not do anything...
399///
400Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
401 Instruction *InsertBefore) {
402 if (V->getType() == DestTy) return V;
403 if (Constant *C = dyn_cast<Constant>(V))
404 return ConstantExpr::getCast(C, DestTy);
405
Reid Spencer811b0cb2006-10-26 19:19:06 +0000406 return InsertCastBefore(V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000407}
408
Chris Lattner4f98c562003-03-10 21:43:22 +0000409// SimplifyCommutative - This performs a few simplifications for commutative
410// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000411//
Chris Lattner4f98c562003-03-10 21:43:22 +0000412// 1. Order operands such that they are listed from right (least complex) to
413// left (most complex). This puts constants before unary operators before
414// binary operators.
415//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000416// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
417// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000418//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000419bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000420 bool Changed = false;
421 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
422 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000423
Chris Lattner4f98c562003-03-10 21:43:22 +0000424 if (!I.isAssociative()) return Changed;
425 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000426 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
427 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
428 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000429 Constant *Folded = ConstantExpr::get(I.getOpcode(),
430 cast<Constant>(I.getOperand(1)),
431 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000432 I.setOperand(0, Op->getOperand(0));
433 I.setOperand(1, Folded);
434 return true;
435 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
436 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
437 isOnlyUse(Op) && isOnlyUse(Op1)) {
438 Constant *C1 = cast<Constant>(Op->getOperand(1));
439 Constant *C2 = cast<Constant>(Op1->getOperand(1));
440
441 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000442 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000443 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
444 Op1->getOperand(0),
445 Op1->getName(), &I);
446 WorkList.push_back(New);
447 I.setOperand(0, New);
448 I.setOperand(1, Folded);
449 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000450 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000451 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000452 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000453}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000454
Chris Lattner8d969642003-03-10 23:06:50 +0000455// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
456// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000457//
Chris Lattner8d969642003-03-10 23:06:50 +0000458static inline Value *dyn_castNegVal(Value *V) {
459 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000460 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000461
Chris Lattner0ce85802004-12-14 20:08:06 +0000462 // Constants can be considered to be negated values if they can be folded.
463 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
464 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000465 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000466}
467
Chris Lattner8d969642003-03-10 23:06:50 +0000468static inline Value *dyn_castNotVal(Value *V) {
469 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000470 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000471
472 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000473 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000474 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000475 return 0;
476}
477
Chris Lattnerc8802d22003-03-11 00:12:48 +0000478// dyn_castFoldableMul - If this value is a multiply that can be folded into
479// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000480// non-constant operand of the multiply, and set CST to point to the multiplier.
481// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000482//
Chris Lattner50af16a2004-11-13 19:50:12 +0000483static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000484 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000485 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000486 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000487 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000488 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000489 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000490 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000491 // The multiplier is really 1 << CST.
492 Constant *One = ConstantInt::get(V->getType(), 1);
493 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
494 return I->getOperand(0);
495 }
496 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000497 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000498}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000499
Chris Lattner574da9b2005-01-13 20:14:25 +0000500/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
501/// expression, return it.
502static User *dyn_castGetElementPtr(Value *V) {
503 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
504 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
505 if (CE->getOpcode() == Instruction::GetElementPtr)
506 return cast<User>(V);
507 return false;
508}
509
Chris Lattner955f3312004-09-28 21:48:02 +0000510// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000511static ConstantInt *AddOne(ConstantInt *C) {
512 return cast<ConstantInt>(ConstantExpr::getAdd(C,
513 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000514}
Chris Lattnera96879a2004-09-29 17:40:11 +0000515static ConstantInt *SubOne(ConstantInt *C) {
516 return cast<ConstantInt>(ConstantExpr::getSub(C,
517 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000518}
519
Chris Lattner255d8912006-02-11 09:31:47 +0000520/// GetConstantInType - Return a ConstantInt with the specified type and value.
521///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000522static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000523 if (Ty->isUnsigned())
524 return ConstantInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000525 else if (Ty->getTypeID() == Type::BoolTyID)
526 return ConstantBool::get(Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000527 int64_t SVal = Val;
528 SVal <<= 64-Ty->getPrimitiveSizeInBits();
529 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +0000530 return ConstantInt::get(Ty, SVal);
Chris Lattner255d8912006-02-11 09:31:47 +0000531}
532
533
Chris Lattner68d5ff22006-02-09 07:38:58 +0000534/// ComputeMaskedBits - Determine which of the bits specified in Mask are
535/// known to be either zero or one and return them in the KnownZero/KnownOne
536/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
537/// processing.
538static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
539 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000540 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
541 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000542 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000543 // optimized based on the contradictory assumption that it is non-zero.
544 // Because instcombine aggressively folds operations with undef args anyway,
545 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000546 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
547 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000548 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000549 KnownZero = ~KnownOne & Mask;
550 return;
551 }
552
553 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000554 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000555 return; // Limit search depth.
556
557 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000558 Instruction *I = dyn_cast<Instruction>(V);
559 if (!I) return;
560
Chris Lattnere3158302006-05-04 17:33:35 +0000561 Mask &= V->getType()->getIntegralTypeMask();
562
Chris Lattner255d8912006-02-11 09:31:47 +0000563 switch (I->getOpcode()) {
564 case Instruction::And:
565 // If either the LHS or the RHS are Zero, the result is zero.
566 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
567 Mask &= ~KnownZero;
568 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
569 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
570 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
571
572 // Output known-1 bits are only known if set in both the LHS & RHS.
573 KnownOne &= KnownOne2;
574 // Output known-0 are known to be clear if zero in either the LHS | RHS.
575 KnownZero |= KnownZero2;
576 return;
577 case Instruction::Or:
578 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
579 Mask &= ~KnownOne;
580 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
581 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
582 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
583
584 // Output known-0 bits are only known if clear in both the LHS & RHS.
585 KnownZero &= KnownZero2;
586 // Output known-1 are known to be set if set in either the LHS | RHS.
587 KnownOne |= KnownOne2;
588 return;
589 case Instruction::Xor: {
590 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
591 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
592 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
593 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
594
595 // Output known-0 bits are known if clear or set in both the LHS & RHS.
596 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
597 // Output known-1 are known to be set if set in only one of the LHS, RHS.
598 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
599 KnownZero = KnownZeroOut;
600 return;
601 }
602 case Instruction::Select:
603 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
604 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
605 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
606 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
607
608 // Only known if known in both the LHS and RHS.
609 KnownOne &= KnownOne2;
610 KnownZero &= KnownZero2;
611 return;
Reid Spencer3da59db2006-11-27 01:05:10 +0000612 case Instruction::FPTrunc:
613 case Instruction::FPExt:
614 case Instruction::FPToUI:
615 case Instruction::FPToSI:
616 case Instruction::SIToFP:
617 case Instruction::PtrToInt:
618 case Instruction::UIToFP:
619 case Instruction::IntToPtr:
620 return; // Can't work with floating point or pointers
621 case Instruction::Trunc:
622 // All these have integer operands
623 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
624 return;
625 case Instruction::BitCast: {
Chris Lattner255d8912006-02-11 09:31:47 +0000626 const Type *SrcTy = I->getOperand(0)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +0000627 if (SrcTy->isIntegral()) {
Chris Lattner255d8912006-02-11 09:31:47 +0000628 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000629 return;
630 }
Reid Spencer3da59db2006-11-27 01:05:10 +0000631 break;
632 }
633 case Instruction::ZExt: {
634 // Compute the bits in the result that are not present in the input.
635 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +0000636 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
637 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000638
Reid Spencer3da59db2006-11-27 01:05:10 +0000639 Mask &= SrcTy->getIntegralTypeMask();
640 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
642 // The top bits are known to be zero.
643 KnownZero |= NewBits;
644 return;
645 }
646 case Instruction::SExt: {
647 // Compute the bits in the result that are not present in the input.
648 const Type *SrcTy = I->getOperand(0)->getType();
649 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
650 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
651
652 Mask &= SrcTy->getIntegralTypeMask();
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000655
Reid Spencer3da59db2006-11-27 01:05:10 +0000656 // If the sign bit of the input is known set or clear, then we know the
657 // top bits of the result.
658 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
659 if (KnownZero & InSignBit) { // Input sign bit known zero
660 KnownZero |= NewBits;
661 KnownOne &= ~NewBits;
662 } else if (KnownOne & InSignBit) { // Input sign bit known set
663 KnownOne |= NewBits;
664 KnownZero &= ~NewBits;
665 } else { // Input sign bit unknown
666 KnownZero &= ~NewBits;
667 KnownOne &= ~NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000668 }
669 return;
670 }
671 case Instruction::Shl:
672 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000673 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
674 uint64_t ShiftAmt = SA->getZExtValue();
675 Mask >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000676 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
677 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000678 KnownZero <<= ShiftAmt;
679 KnownOne <<= ShiftAmt;
680 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +0000681 return;
682 }
683 break;
Reid Spencer3822ff52006-11-08 06:47:33 +0000684 case Instruction::LShr:
Chris Lattner255d8912006-02-11 09:31:47 +0000685 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000686 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner255d8912006-02-11 09:31:47 +0000687 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +0000688 uint64_t ShiftAmt = SA->getZExtValue();
689 uint64_t HighBits = (1ULL << ShiftAmt)-1;
690 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000691
Reid Spencer3822ff52006-11-08 06:47:33 +0000692 // Unsigned shift right.
693 Mask <<= ShiftAmt;
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
695 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
696 KnownZero >>= ShiftAmt;
697 KnownOne >>= ShiftAmt;
698 KnownZero |= HighBits; // high bits known zero.
699 return;
700 }
701 break;
702 case Instruction::AShr:
703 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
704 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
705 // Compute the new bits that are at the top now.
706 uint64_t ShiftAmt = SA->getZExtValue();
707 uint64_t HighBits = (1ULL << ShiftAmt)-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
709
710 // Signed shift right.
711 Mask <<= ShiftAmt;
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= ShiftAmt;
715 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000716
Reid Spencer3822ff52006-11-08 06:47:33 +0000717 // Handle the sign bits.
718 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
719 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +0000720
Reid Spencer3822ff52006-11-08 06:47:33 +0000721 if (KnownZero & SignBit) { // New bits are known zero.
722 KnownZero |= HighBits;
723 } else if (KnownOne & SignBit) { // New bits are known one.
724 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000725 }
726 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000727 }
Chris Lattner255d8912006-02-11 09:31:47 +0000728 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000729 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000730}
731
732/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
733/// this predicate to simplify operations downstream. Mask is known to be zero
734/// for bits that V cannot have.
735static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000736 uint64_t KnownZero, KnownOne;
737 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
738 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
739 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000740}
741
Chris Lattner255d8912006-02-11 09:31:47 +0000742/// ShrinkDemandedConstant - Check to see if the specified operand of the
743/// specified instruction is a constant integer. If so, check to see if there
744/// are any bits set in the constant that are not demanded. If so, shrink the
745/// constant and return true.
746static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
747 uint64_t Demanded) {
748 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
749 if (!OpC) return false;
750
751 // If there are no bits set that aren't demanded, nothing to do.
752 if ((~Demanded & OpC->getZExtValue()) == 0)
753 return false;
754
755 // This is producing any bits that are not needed, shrink the RHS.
756 uint64_t Val = Demanded & OpC->getZExtValue();
757 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
758 return true;
759}
760
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000761// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
762// set of known zero and one bits, compute the maximum and minimum values that
763// could have the specified known zero and known one bits, returning them in
764// min/max.
765static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
766 uint64_t KnownZero,
767 uint64_t KnownOne,
768 int64_t &Min, int64_t &Max) {
769 uint64_t TypeBits = Ty->getIntegralTypeMask();
770 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
771
772 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
773
774 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
775 // bit if it is unknown.
776 Min = KnownOne;
777 Max = KnownOne|UnknownBits;
778
779 if (SignBit & UnknownBits) { // Sign bit is unknown
780 Min |= SignBit;
781 Max &= ~SignBit;
782 }
783
784 // Sign extend the min/max values.
785 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
786 Min = (Min << ShAmt) >> ShAmt;
787 Max = (Max << ShAmt) >> ShAmt;
788}
789
790// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
791// a set of known zero and one bits, compute the maximum and minimum values that
792// could have the specified known zero and known one bits, returning them in
793// min/max.
794static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
795 uint64_t KnownZero,
796 uint64_t KnownOne,
797 uint64_t &Min,
798 uint64_t &Max) {
799 uint64_t TypeBits = Ty->getIntegralTypeMask();
800 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
801
802 // The minimum value is when the unknown bits are all zeros.
803 Min = KnownOne;
804 // The maximum value is when the unknown bits are all ones.
805 Max = KnownOne|UnknownBits;
806}
Chris Lattner255d8912006-02-11 09:31:47 +0000807
808
809/// SimplifyDemandedBits - Look at V. At this point, we know that only the
810/// DemandedMask bits of the result of V are ever used downstream. If we can
811/// use this information to simplify V, do so and return true. Otherwise,
812/// analyze the expression and return a mask of KnownOne and KnownZero bits for
813/// the expression (used to simplify the caller). The KnownZero/One bits may
814/// only be accurate for those bits in the DemandedMask.
815bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
816 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000817 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000818 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
819 // We know all of the bits for a constant!
820 KnownOne = CI->getZExtValue() & DemandedMask;
821 KnownZero = ~KnownOne & DemandedMask;
822 return false;
823 }
824
825 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000826 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000827 if (Depth != 0) { // Not at the root.
828 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
829 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000830 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000831 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000832 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000833 // just set the DemandedMask to all bits.
834 DemandedMask = V->getType()->getIntegralTypeMask();
835 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000836 if (V != UndefValue::get(V->getType()))
837 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
838 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000839 } else if (Depth == 6) { // Limit search depth.
840 return false;
841 }
842
843 Instruction *I = dyn_cast<Instruction>(V);
844 if (!I) return false; // Only analyze instructions.
845
Chris Lattnere3158302006-05-04 17:33:35 +0000846 DemandedMask &= V->getType()->getIntegralTypeMask();
847
Reid Spencer3da59db2006-11-27 01:05:10 +0000848 uint64_t KnownZero2 = 0, KnownOne2 = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000849 switch (I->getOpcode()) {
850 default: break;
851 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000852 // If either the LHS or the RHS are Zero, the result is zero.
853 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
854 KnownZero, KnownOne, Depth+1))
855 return true;
856 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
857
858 // If something is known zero on the RHS, the bits aren't demanded on the
859 // LHS.
860 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
861 KnownZero2, KnownOne2, Depth+1))
862 return true;
863 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
864
Reid Spencer3da59db2006-11-27 01:05:10 +0000865 // If all of the demanded bits are known 1 on one side, return the other.
Chris Lattner255d8912006-02-11 09:31:47 +0000866 // These bits cannot contribute to the result of the 'and'.
867 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
870 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000871
872 // If all of the demanded bits in the inputs are known zeros, return zero.
873 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
874 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
875
Chris Lattner255d8912006-02-11 09:31:47 +0000876 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000877 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000878 return UpdateValueUsesWith(I, I);
879
880 // Output known-1 bits are only known if set in both the LHS & RHS.
881 KnownOne &= KnownOne2;
882 // Output known-0 are known to be clear if zero in either the LHS | RHS.
883 KnownZero |= KnownZero2;
884 break;
885 case Instruction::Or:
886 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
887 KnownZero, KnownOne, Depth+1))
888 return true;
889 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
890 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
891 KnownZero2, KnownOne2, Depth+1))
892 return true;
893 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
894
895 // If all of the demanded bits are known zero on one side, return the other.
896 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000897 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000898 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000899 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000900 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000901
902 // If all of the potentially set bits on one side are known to be set on
903 // the other side, just use the 'other' side.
904 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
905 (DemandedMask & (~KnownZero)))
906 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000907 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
908 (DemandedMask & (~KnownZero2)))
909 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000910
911 // If the RHS is a constant, see if we can simplify it.
912 if (ShrinkDemandedConstant(I, 1, DemandedMask))
913 return UpdateValueUsesWith(I, I);
914
915 // Output known-0 bits are only known if clear in both the LHS & RHS.
916 KnownZero &= KnownZero2;
917 // Output known-1 are known to be set if set in either the LHS | RHS.
918 KnownOne |= KnownOne2;
919 break;
920 case Instruction::Xor: {
921 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
922 KnownZero, KnownOne, Depth+1))
923 return true;
924 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
925 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
926 KnownZero2, KnownOne2, Depth+1))
927 return true;
928 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
929
930 // If all of the demanded bits are known zero on one side, return the other.
931 // These bits cannot contribute to the result of the 'xor'.
932 if ((DemandedMask & KnownZero) == DemandedMask)
933 return UpdateValueUsesWith(I, I->getOperand(0));
934 if ((DemandedMask & KnownZero2) == DemandedMask)
935 return UpdateValueUsesWith(I, I->getOperand(1));
936
937 // Output known-0 bits are known if clear or set in both the LHS & RHS.
938 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
939 // Output known-1 are known to be set if set in only one of the LHS, RHS.
940 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
941
Chris Lattnerf2f16432006-11-27 19:55:07 +0000942 // If all of the demanded bits are known to be zero on one side or the
943 // other, turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000944 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerf2f16432006-11-27 19:55:07 +0000945 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
946 Instruction *Or =
947 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
948 I->getName());
949 InsertNewInstBefore(Or, *I);
950 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000951 }
Chris Lattner255d8912006-02-11 09:31:47 +0000952
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000953 // If all of the demanded bits on one side are known, and all of the set
954 // bits on that side are also known to be set on the other side, turn this
955 // into an AND, as we know the bits will be cleared.
956 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
958 if ((KnownOne & KnownOne2) == KnownOne) {
959 Constant *AndC = GetConstantInType(I->getType(),
960 ~KnownOne & DemandedMask);
961 Instruction *And =
962 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
963 InsertNewInstBefore(And, *I);
964 return UpdateValueUsesWith(I, And);
965 }
966 }
967
Chris Lattner255d8912006-02-11 09:31:47 +0000968 // If the RHS is a constant, see if we can simplify it.
969 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
970 if (ShrinkDemandedConstant(I, 1, DemandedMask))
971 return UpdateValueUsesWith(I, I);
972
973 KnownZero = KnownZeroOut;
974 KnownOne = KnownOneOut;
975 break;
976 }
977 case Instruction::Select:
978 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
979 KnownZero, KnownOne, Depth+1))
980 return true;
981 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
982 KnownZero2, KnownOne2, Depth+1))
983 return true;
984 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
985 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
986
987 // If the operands are constants, see if we can simplify them.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask))
989 return UpdateValueUsesWith(I, I);
990 if (ShrinkDemandedConstant(I, 2, DemandedMask))
991 return UpdateValueUsesWith(I, I);
992
993 // Only known if known in both the LHS and RHS.
994 KnownOne &= KnownOne2;
995 KnownZero &= KnownZero2;
996 break;
Reid Spencer3da59db2006-11-27 01:05:10 +0000997 case Instruction::Trunc:
998 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999 KnownZero, KnownOne, Depth+1))
1000 return true;
1001 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1002 break;
1003 case Instruction::BitCast:
1004 if (!I->getOperand(0)->getType()->isIntegral())
1005 return false;
Chris Lattnerf6bd07c2006-09-16 03:14:10 +00001006
Reid Spencer3da59db2006-11-27 01:05:10 +00001007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 KnownZero, KnownOne, Depth+1))
1009 return true;
1010 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1011 break;
1012 case Instruction::ZExt: {
1013 // Compute the bits in the result that are not present in the input.
1014 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +00001015 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1016 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1017
Reid Spencer3da59db2006-11-27 01:05:10 +00001018 DemandedMask &= SrcTy->getIntegralTypeMask();
1019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1021 return true;
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1023 // The top bits are known to be zero.
1024 KnownZero |= NewBits;
1025 break;
1026 }
1027 case Instruction::SExt: {
1028 // Compute the bits in the result that are not present in the input.
1029 const Type *SrcTy = I->getOperand(0)->getType();
1030 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1031 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1032
1033 // Get the sign bit for the source type
1034 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1035 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
Chris Lattnerf345fe42006-02-13 22:41:07 +00001036
Reid Spencer3da59db2006-11-27 01:05:10 +00001037 // If any of the sign extended bits are demanded, we know that the sign
1038 // bit is demanded.
1039 if (NewBits & DemandedMask)
1040 InputDemandedBits |= InSignBit;
Chris Lattnerf345fe42006-02-13 22:41:07 +00001041
Reid Spencer3da59db2006-11-27 01:05:10 +00001042 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043 KnownZero, KnownOne, Depth+1))
1044 return true;
1045 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner255d8912006-02-11 09:31:47 +00001046
Reid Spencer3da59db2006-11-27 01:05:10 +00001047 // If the sign bit of the input is known set or clear, then we know the
1048 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001049
Reid Spencer3da59db2006-11-27 01:05:10 +00001050 // If the input sign bit is known zero, or if the NewBits are not demanded
1051 // convert this into a zero extension.
1052 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1053 // Convert to ZExt cast
1054 CastInst *NewCast = CastInst::create(
1055 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1056 return UpdateValueUsesWith(I, NewCast);
1057 } else if (KnownOne & InSignBit) { // Input sign bit known set
1058 KnownOne |= NewBits;
1059 KnownZero &= ~NewBits;
1060 } else { // Input sign bit unknown
1061 KnownZero &= ~NewBits;
1062 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001063 }
Chris Lattner255d8912006-02-11 09:31:47 +00001064 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001065 }
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001066 case Instruction::Add:
1067 // If there is a constant on the RHS, there are a variety of xformations
1068 // we can do.
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1072 if (RHS->isNullValue())
1073 break;
1074
1075 // Figure out what the input bits are. If the top bits of the and result
1076 // are not demanded, then the add doesn't demand them from its input
1077 // either.
1078
1079 // Shift the demanded mask up so that it's at the top of the uint64_t.
1080 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1081 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1082
1083 // If the top bit of the output is demanded, demand everything from the
1084 // input. Otherwise, we demand all the input bits except NLZ top bits.
1085 uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1086
1087 // Find information about known zero/one bits in the input.
1088 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1089 KnownZero2, KnownOne2, Depth+1))
1090 return true;
1091
1092 // If the RHS of the add has bits set that can't affect the input, reduce
1093 // the constant.
1094 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1095 return UpdateValueUsesWith(I, I);
1096
1097 // Avoid excess work.
1098 if (KnownZero2 == 0 && KnownOne2 == 0)
1099 break;
1100
1101 // Turn it into OR if input bits are zero.
1102 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1103 Instruction *Or =
1104 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1105 I->getName());
1106 InsertNewInstBefore(Or, *I);
1107 return UpdateValueUsesWith(I, Or);
1108 }
1109
1110 // We can say something about the output known-zero and known-one bits,
1111 // depending on potential carries from the input constant and the
1112 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1113 // bits set and the RHS constant is 0x01001, then we know we have a known
1114 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1115
1116 // To compute this, we first compute the potential carry bits. These are
1117 // the bits which may be modified. I'm not aware of a better way to do
1118 // this scan.
1119 uint64_t RHSVal = RHS->getZExtValue();
1120
1121 bool CarryIn = false;
1122 uint64_t CarryBits = 0;
1123 uint64_t CurBit = 1;
1124 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1125 // Record the current carry in.
1126 if (CarryIn) CarryBits |= CurBit;
1127
1128 bool CarryOut;
1129
1130 // This bit has a carry out unless it is "zero + zero" or
1131 // "zero + anything" with no carry in.
1132 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1133 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1134 } else if (!CarryIn &&
1135 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1136 CarryOut = false; // 0 + anything has no carry out if no carry in.
1137 } else {
1138 // Otherwise, we have to assume we have a carry out.
1139 CarryOut = true;
1140 }
1141
1142 // This stage's carry out becomes the next stage's carry-in.
1143 CarryIn = CarryOut;
1144 }
1145
1146 // Now that we know which bits have carries, compute the known-1/0 sets.
1147
1148 // Bits are known one if they are known zero in one operand and one in the
1149 // other, and there is no input carry.
1150 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1151
1152 // Bits are known zero if they are known zero in both operands and there
1153 // is no input carry.
1154 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1155 }
1156 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001157 case Instruction::Shl:
Reid Spencerb83eb642006-10-20 07:07:24 +00001158 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 uint64_t ShiftAmt = SA->getZExtValue();
1160 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner255d8912006-02-11 09:31:47 +00001161 KnownZero, KnownOne, Depth+1))
1162 return true;
1163 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +00001164 KnownZero <<= ShiftAmt;
1165 KnownOne <<= ShiftAmt;
1166 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +00001167 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001168 break;
Reid Spencer3822ff52006-11-08 06:47:33 +00001169 case Instruction::LShr:
1170 // For a logical shift right
1171 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 unsigned ShiftAmt = SA->getZExtValue();
1173
1174 // Compute the new bits that are at the top now.
1175 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1176 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1177 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1178 // Unsigned shift right.
1179 if (SimplifyDemandedBits(I->getOperand(0),
1180 (DemandedMask << ShiftAmt) & TypeMask,
1181 KnownZero, KnownOne, Depth+1))
1182 return true;
1183 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1184 KnownZero &= TypeMask;
1185 KnownOne &= TypeMask;
1186 KnownZero >>= ShiftAmt;
1187 KnownOne >>= ShiftAmt;
1188 KnownZero |= HighBits; // high bits known zero.
1189 }
1190 break;
1191 case Instruction::AShr:
Chris Lattnerb7363792006-09-18 04:31:40 +00001192 // If this is an arithmetic shift right and only the low-bit is set, we can
1193 // always convert this into a logical shr, even if the shift amount is
1194 // variable. The low bit of the shift cannot be an input sign bit unless
1195 // the shift amount is >= the size of the datatype, which is undefined.
Reid Spencer3822ff52006-11-08 06:47:33 +00001196 if (DemandedMask == 1) {
1197 // Perform the logical shift right.
1198 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1199 I->getOperand(1), I->getName());
Reid Spencer811b0cb2006-10-26 19:19:06 +00001200 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
Chris Lattnerb7363792006-09-18 04:31:40 +00001201 return UpdateValueUsesWith(I, NewVal);
1202 }
1203
Reid Spencerb83eb642006-10-20 07:07:24 +00001204 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1205 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner255d8912006-02-11 09:31:47 +00001206
1207 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +00001208 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1209 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +00001210 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Reid Spencer3822ff52006-11-08 06:47:33 +00001211 // Signed shift right.
1212 if (SimplifyDemandedBits(I->getOperand(0),
1213 (DemandedMask << ShiftAmt) & TypeMask,
1214 KnownZero, KnownOne, Depth+1))
1215 return true;
1216 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1217 KnownZero &= TypeMask;
1218 KnownOne &= TypeMask;
1219 KnownZero >>= ShiftAmt;
1220 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001221
Reid Spencer3822ff52006-11-08 06:47:33 +00001222 // Handle the sign bits.
1223 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1224 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +00001225
Reid Spencer3822ff52006-11-08 06:47:33 +00001226 // If the input sign bit is known to be zero, or if none of the top bits
1227 // are demanded, turn this into an unsigned shift right.
1228 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1229 // Perform the logical shift right.
1230 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1231 SA, I->getName());
1232 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1233 return UpdateValueUsesWith(I, NewVal);
1234 } else if (KnownOne & SignBit) { // New bits are known one.
1235 KnownOne |= HighBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001236 }
Chris Lattner255d8912006-02-11 09:31:47 +00001237 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001238 break;
1239 }
Chris Lattner255d8912006-02-11 09:31:47 +00001240
1241 // If the client is only demanding bits that we know, return the known
1242 // constant.
1243 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1244 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001245 return false;
1246}
1247
Chris Lattner867b99f2006-10-05 06:55:50 +00001248
1249/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1250/// 64 or fewer elements. DemandedElts contains the set of elements that are
1251/// actually used by the caller. This method analyzes which elements of the
1252/// operand are undef and returns that information in UndefElts.
1253///
1254/// If the information about demanded elements can be used to simplify the
1255/// operation, the operation is simplified, then the resultant value is
1256/// returned. This returns null if no change was made.
1257Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1258 uint64_t &UndefElts,
1259 unsigned Depth) {
1260 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1261 assert(VWidth <= 64 && "Vector too wide to analyze!");
1262 uint64_t EltMask = ~0ULL >> (64-VWidth);
1263 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1264 "Invalid DemandedElts!");
1265
1266 if (isa<UndefValue>(V)) {
1267 // If the entire vector is undefined, just return this info.
1268 UndefElts = EltMask;
1269 return 0;
1270 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1271 UndefElts = EltMask;
1272 return UndefValue::get(V->getType());
1273 }
1274
1275 UndefElts = 0;
1276 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1277 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1278 Constant *Undef = UndefValue::get(EltTy);
1279
1280 std::vector<Constant*> Elts;
1281 for (unsigned i = 0; i != VWidth; ++i)
1282 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1283 Elts.push_back(Undef);
1284 UndefElts |= (1ULL << i);
1285 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1286 Elts.push_back(Undef);
1287 UndefElts |= (1ULL << i);
1288 } else { // Otherwise, defined.
1289 Elts.push_back(CP->getOperand(i));
1290 }
1291
1292 // If we changed the constant, return it.
1293 Constant *NewCP = ConstantPacked::get(Elts);
1294 return NewCP != CP ? NewCP : 0;
1295 } else if (isa<ConstantAggregateZero>(V)) {
1296 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1297 // set to undef.
1298 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1299 Constant *Zero = Constant::getNullValue(EltTy);
1300 Constant *Undef = UndefValue::get(EltTy);
1301 std::vector<Constant*> Elts;
1302 for (unsigned i = 0; i != VWidth; ++i)
1303 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1304 UndefElts = DemandedElts ^ EltMask;
1305 return ConstantPacked::get(Elts);
1306 }
1307
1308 if (!V->hasOneUse()) { // Other users may use these bits.
1309 if (Depth != 0) { // Not at the root.
1310 // TODO: Just compute the UndefElts information recursively.
1311 return false;
1312 }
1313 return false;
1314 } else if (Depth == 10) { // Limit search depth.
1315 return false;
1316 }
1317
1318 Instruction *I = dyn_cast<Instruction>(V);
1319 if (!I) return false; // Only analyze instructions.
1320
1321 bool MadeChange = false;
1322 uint64_t UndefElts2;
1323 Value *TmpV;
1324 switch (I->getOpcode()) {
1325 default: break;
1326
1327 case Instruction::InsertElement: {
1328 // If this is a variable index, we don't know which element it overwrites.
1329 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001330 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001331 if (Idx == 0) {
1332 // Note that we can't propagate undef elt info, because we don't know
1333 // which elt is getting updated.
1334 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1335 UndefElts2, Depth+1);
1336 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1337 break;
1338 }
1339
1340 // If this is inserting an element that isn't demanded, remove this
1341 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001342 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001343 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1344 return AddSoonDeadInstToWorklist(*I, 0);
1345
1346 // Otherwise, the element inserted overwrites whatever was there, so the
1347 // input demanded set is simpler than the output set.
1348 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1349 DemandedElts & ~(1ULL << IdxNo),
1350 UndefElts, Depth+1);
1351 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1352
1353 // The inserted element is defined.
1354 UndefElts |= 1ULL << IdxNo;
1355 break;
1356 }
1357
1358 case Instruction::And:
1359 case Instruction::Or:
1360 case Instruction::Xor:
1361 case Instruction::Add:
1362 case Instruction::Sub:
1363 case Instruction::Mul:
1364 // div/rem demand all inputs, because they don't want divide by zero.
1365 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1366 UndefElts, Depth+1);
1367 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1368 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1369 UndefElts2, Depth+1);
1370 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1371
1372 // Output elements are undefined if both are undefined. Consider things
1373 // like undef&0. The result is known zero, not undef.
1374 UndefElts &= UndefElts2;
1375 break;
1376
1377 case Instruction::Call: {
1378 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1379 if (!II) break;
1380 switch (II->getIntrinsicID()) {
1381 default: break;
1382
1383 // Binary vector operations that work column-wise. A dest element is a
1384 // function of the corresponding input elements from the two inputs.
1385 case Intrinsic::x86_sse_sub_ss:
1386 case Intrinsic::x86_sse_mul_ss:
1387 case Intrinsic::x86_sse_min_ss:
1388 case Intrinsic::x86_sse_max_ss:
1389 case Intrinsic::x86_sse2_sub_sd:
1390 case Intrinsic::x86_sse2_mul_sd:
1391 case Intrinsic::x86_sse2_min_sd:
1392 case Intrinsic::x86_sse2_max_sd:
1393 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1394 UndefElts, Depth+1);
1395 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1396 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1397 UndefElts2, Depth+1);
1398 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1399
1400 // If only the low elt is demanded and this is a scalarizable intrinsic,
1401 // scalarize it now.
1402 if (DemandedElts == 1) {
1403 switch (II->getIntrinsicID()) {
1404 default: break;
1405 case Intrinsic::x86_sse_sub_ss:
1406 case Intrinsic::x86_sse_mul_ss:
1407 case Intrinsic::x86_sse2_sub_sd:
1408 case Intrinsic::x86_sse2_mul_sd:
1409 // TODO: Lower MIN/MAX/ABS/etc
1410 Value *LHS = II->getOperand(1);
1411 Value *RHS = II->getOperand(2);
1412 // Extract the element as scalars.
1413 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1414 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1415
1416 switch (II->getIntrinsicID()) {
1417 default: assert(0 && "Case stmts out of sync!");
1418 case Intrinsic::x86_sse_sub_ss:
1419 case Intrinsic::x86_sse2_sub_sd:
1420 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1421 II->getName()), *II);
1422 break;
1423 case Intrinsic::x86_sse_mul_ss:
1424 case Intrinsic::x86_sse2_mul_sd:
1425 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1426 II->getName()), *II);
1427 break;
1428 }
1429
1430 Instruction *New =
1431 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1432 II->getName());
1433 InsertNewInstBefore(New, *II);
1434 AddSoonDeadInstToWorklist(*II, 0);
1435 return New;
1436 }
1437 }
1438
1439 // Output elements are undefined if both are undefined. Consider things
1440 // like undef&0. The result is known zero, not undef.
1441 UndefElts &= UndefElts2;
1442 break;
1443 }
1444 break;
1445 }
1446 }
1447 return MadeChange ? I : 0;
1448}
1449
Chris Lattner955f3312004-09-28 21:48:02 +00001450// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1451// true when both operands are equal...
1452//
1453static bool isTrueWhenEqual(Instruction &I) {
1454 return I.getOpcode() == Instruction::SetEQ ||
1455 I.getOpcode() == Instruction::SetGE ||
1456 I.getOpcode() == Instruction::SetLE;
1457}
Chris Lattner564a7272003-08-13 19:01:45 +00001458
1459/// AssociativeOpt - Perform an optimization on an associative operator. This
1460/// function is designed to check a chain of associative operators for a
1461/// potential to apply a certain optimization. Since the optimization may be
1462/// applicable if the expression was reassociated, this checks the chain, then
1463/// reassociates the expression as necessary to expose the optimization
1464/// opportunity. This makes use of a special Functor, which must define
1465/// 'shouldApply' and 'apply' methods.
1466///
1467template<typename Functor>
1468Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1469 unsigned Opcode = Root.getOpcode();
1470 Value *LHS = Root.getOperand(0);
1471
1472 // Quick check, see if the immediate LHS matches...
1473 if (F.shouldApply(LHS))
1474 return F.apply(Root);
1475
1476 // Otherwise, if the LHS is not of the same opcode as the root, return.
1477 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001478 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001479 // Should we apply this transform to the RHS?
1480 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1481
1482 // If not to the RHS, check to see if we should apply to the LHS...
1483 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1484 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1485 ShouldApply = true;
1486 }
1487
1488 // If the functor wants to apply the optimization to the RHS of LHSI,
1489 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1490 if (ShouldApply) {
1491 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001492
Chris Lattner564a7272003-08-13 19:01:45 +00001493 // Now all of the instructions are in the current basic block, go ahead
1494 // and perform the reassociation.
1495 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1496
1497 // First move the selected RHS to the LHS of the root...
1498 Root.setOperand(0, LHSI->getOperand(1));
1499
1500 // Make what used to be the LHS of the root be the user of the root...
1501 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001502 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001503 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1504 return 0;
1505 }
Chris Lattner65725312004-04-16 18:08:07 +00001506 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001507 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001508 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1509 BasicBlock::iterator ARI = &Root; ++ARI;
1510 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1511 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001512
1513 // Now propagate the ExtraOperand down the chain of instructions until we
1514 // get to LHSI.
1515 while (TmpLHSI != LHSI) {
1516 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001517 // Move the instruction to immediately before the chain we are
1518 // constructing to avoid breaking dominance properties.
1519 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1520 BB->getInstList().insert(ARI, NextLHSI);
1521 ARI = NextLHSI;
1522
Chris Lattner564a7272003-08-13 19:01:45 +00001523 Value *NextOp = NextLHSI->getOperand(1);
1524 NextLHSI->setOperand(1, ExtraOperand);
1525 TmpLHSI = NextLHSI;
1526 ExtraOperand = NextOp;
1527 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001528
Chris Lattner564a7272003-08-13 19:01:45 +00001529 // Now that the instructions are reassociated, have the functor perform
1530 // the transformation...
1531 return F.apply(Root);
1532 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001533
Chris Lattner564a7272003-08-13 19:01:45 +00001534 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1535 }
1536 return 0;
1537}
1538
1539
1540// AddRHS - Implements: X + X --> X << 1
1541struct AddRHS {
1542 Value *RHS;
1543 AddRHS(Value *rhs) : RHS(rhs) {}
1544 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1545 Instruction *apply(BinaryOperator &Add) const {
1546 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1547 ConstantInt::get(Type::UByteTy, 1));
1548 }
1549};
1550
1551// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1552// iff C1&C2 == 0
1553struct AddMaskingAnd {
1554 Constant *C2;
1555 AddMaskingAnd(Constant *c) : C2(c) {}
1556 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001557 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001558 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001559 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001560 }
1561 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001562 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001563 }
1564};
1565
Chris Lattner6e7ba452005-01-01 16:22:27 +00001566static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001567 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001568 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001569 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001570 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001571
Reid Spencer3da59db2006-11-27 01:05:10 +00001572 return IC->InsertNewInstBefore(CastInst::create(
1573 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001574 }
1575
Chris Lattner2eefe512004-04-09 19:05:30 +00001576 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001577 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1578 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001579
Chris Lattner2eefe512004-04-09 19:05:30 +00001580 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1581 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001582 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1583 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001584 }
1585
1586 Value *Op0 = SO, *Op1 = ConstOperand;
1587 if (!ConstIsRHS)
1588 std::swap(Op0, Op1);
1589 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001590 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1591 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1592 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1593 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001594 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001595 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001596 abort();
1597 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001598 return IC->InsertNewInstBefore(New, I);
1599}
1600
1601// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1602// constant as the other operand, try to fold the binary operator into the
1603// select arguments. This also works for Cast instructions, which obviously do
1604// not have a second operand.
1605static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1606 InstCombiner *IC) {
1607 // Don't modify shared select instructions
1608 if (!SI->hasOneUse()) return 0;
1609 Value *TV = SI->getOperand(1);
1610 Value *FV = SI->getOperand(2);
1611
1612 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001613 // Bool selects with constant operands can be folded to logical ops.
1614 if (SI->getType() == Type::BoolTy) return 0;
1615
Chris Lattner6e7ba452005-01-01 16:22:27 +00001616 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1617 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1618
1619 return new SelectInst(SI->getCondition(), SelectTrueVal,
1620 SelectFalseVal);
1621 }
1622 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001623}
1624
Chris Lattner4e998b22004-09-29 05:07:12 +00001625
1626/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1627/// node as operand #0, see if we can fold the instruction into the PHI (which
1628/// is only possible if all operands to the PHI are constants).
1629Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1630 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001631 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001632 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001633
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001634 // Check to see if all of the operands of the PHI are constants. If there is
1635 // one non-constant value, remember the BB it is. If there is more than one
1636 // bail out.
1637 BasicBlock *NonConstBB = 0;
1638 for (unsigned i = 0; i != NumPHIValues; ++i)
1639 if (!isa<Constant>(PN->getIncomingValue(i))) {
1640 if (NonConstBB) return 0; // More than one non-const value.
1641 NonConstBB = PN->getIncomingBlock(i);
1642
1643 // If the incoming non-constant value is in I's block, we have an infinite
1644 // loop.
1645 if (NonConstBB == I.getParent())
1646 return 0;
1647 }
1648
1649 // If there is exactly one non-constant value, we can insert a copy of the
1650 // operation in that block. However, if this is a critical edge, we would be
1651 // inserting the computation one some other paths (e.g. inside a loop). Only
1652 // do this if the pred block is unconditionally branching into the phi block.
1653 if (NonConstBB) {
1654 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1655 if (!BI || !BI->isUnconditional()) return 0;
1656 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001657
1658 // Okay, we can do the transformation: create the new PHI node.
1659 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1660 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001661 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001662 InsertNewInstBefore(NewPN, *PN);
1663
1664 // Next, add all of the operands to the PHI.
1665 if (I.getNumOperands() == 2) {
1666 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001667 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001668 Value *InV;
1669 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1670 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1671 } else {
1672 assert(PN->getIncomingBlock(i) == NonConstBB);
1673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1674 InV = BinaryOperator::create(BO->getOpcode(),
1675 PN->getIncomingValue(i), C, "phitmp",
1676 NonConstBB->getTerminator());
1677 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1678 InV = new ShiftInst(SI->getOpcode(),
1679 PN->getIncomingValue(i), C, "phitmp",
1680 NonConstBB->getTerminator());
1681 else
1682 assert(0 && "Unknown binop!");
1683
1684 WorkList.push_back(cast<Instruction>(InV));
1685 }
1686 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001687 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001688 } else {
1689 CastInst *CI = cast<CastInst>(&I);
1690 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001691 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001692 Value *InV;
1693 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001694 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001695 } else {
1696 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001697 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1698 I.getType(), "phitmp",
1699 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001700 WorkList.push_back(cast<Instruction>(InV));
1701 }
1702 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001703 }
1704 }
1705 return ReplaceInstUsesWith(I, NewPN);
1706}
1707
Chris Lattner7e708292002-06-25 16:13:24 +00001708Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001709 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001710 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001711
Chris Lattner66331a42004-04-10 22:01:55 +00001712 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001713 // X + undef -> undef
1714 if (isa<UndefValue>(RHS))
1715 return ReplaceInstUsesWith(I, RHS);
1716
Chris Lattner66331a42004-04-10 22:01:55 +00001717 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001718 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1719 if (RHSC->isNullValue())
1720 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001721 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1722 if (CFP->isExactlyValue(-0.0))
1723 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001724 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001725
Chris Lattner66331a42004-04-10 22:01:55 +00001726 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001727 // X + (signbit) --> X ^ signbit
Chris Lattner74c51a02006-02-07 08:05:22 +00001728 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001729 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001730 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00001731
1732 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1733 // (X & 254)+1 -> (X&254)|1
1734 uint64_t KnownZero, KnownOne;
1735 if (!isa<PackedType>(I.getType()) &&
1736 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1737 KnownZero, KnownOne))
1738 return &I;
Chris Lattner66331a42004-04-10 22:01:55 +00001739 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001740
1741 if (isa<PHINode>(LHS))
1742 if (Instruction *NV = FoldOpIntoPhi(I))
1743 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001744
Chris Lattner4f637d42006-01-06 17:59:59 +00001745 ConstantInt *XorRHS = 0;
1746 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001747 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1748 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1749 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1750 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1751
1752 uint64_t C0080Val = 1ULL << 31;
1753 int64_t CFF80Val = -C0080Val;
1754 unsigned Size = 32;
1755 do {
1756 if (TySizeBits > Size) {
1757 bool Found = false;
1758 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1759 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1760 if (RHSSExt == CFF80Val) {
1761 if (XorRHS->getZExtValue() == C0080Val)
1762 Found = true;
1763 } else if (RHSZExt == C0080Val) {
1764 if (XorRHS->getSExtValue() == CFF80Val)
1765 Found = true;
1766 }
1767 if (Found) {
1768 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001769 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001770 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001771 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001772 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001773 Size = 0; // Not a sign ext, but can't be any others either.
1774 goto FoundSExt;
1775 }
1776 }
1777 Size >>= 1;
1778 C0080Val >>= Size;
1779 CFF80Val >>= Size;
1780 } while (Size >= 8);
1781
1782FoundSExt:
1783 const Type *MiddleType = 0;
1784 switch (Size) {
1785 default: break;
1786 case 32: MiddleType = Type::IntTy; break;
1787 case 16: MiddleType = Type::ShortTy; break;
1788 case 8: MiddleType = Type::SByteTy; break;
1789 }
1790 if (MiddleType) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001791 Instruction *NewTrunc =
1792 CastInst::createInferredCast(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00001793 InsertNewInstBefore(NewTrunc, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001794 return new SExtInst(NewTrunc, I.getType());
Chris Lattner5931c542005-09-24 23:43:33 +00001795 }
1796 }
Chris Lattner66331a42004-04-10 22:01:55 +00001797 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001798
Chris Lattner564a7272003-08-13 19:01:45 +00001799 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001800 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001801 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001802
1803 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1804 if (RHSI->getOpcode() == Instruction::Sub)
1805 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1806 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1807 }
1808 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1809 if (LHSI->getOpcode() == Instruction::Sub)
1810 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1811 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1812 }
Robert Bocchino71698282004-07-27 21:02:21 +00001813 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001814
Chris Lattner5c4afb92002-05-08 22:46:53 +00001815 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001816 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001817 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001818
1819 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001820 if (!isa<Constant>(RHS))
1821 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001822 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001823
Misha Brukmanfd939082005-04-21 23:48:37 +00001824
Chris Lattner50af16a2004-11-13 19:50:12 +00001825 ConstantInt *C2;
1826 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1827 if (X == RHS) // X*C + X --> X * (C+1)
1828 return BinaryOperator::createMul(RHS, AddOne(C2));
1829
1830 // X*C1 + X*C2 --> X * (C1+C2)
1831 ConstantInt *C1;
1832 if (X == dyn_castFoldableMul(RHS, C1))
1833 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001834 }
1835
1836 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001837 if (dyn_castFoldableMul(RHS, C2) == LHS)
1838 return BinaryOperator::createMul(LHS, AddOne(C2));
1839
Chris Lattnerad3448c2003-02-18 19:57:07 +00001840
Chris Lattner564a7272003-08-13 19:01:45 +00001841 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001842 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001843 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001844
Chris Lattner6b032052003-10-02 15:11:26 +00001845 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001846 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001847 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1848 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1849 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001850 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001851
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001852 // (X & FF00) + xx00 -> (X+xx00) & FF00
1853 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1854 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1855 if (Anded == CRHS) {
1856 // See if all bits from the first bit set in the Add RHS up are included
1857 // in the mask. First, get the rightmost bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001858 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001859
1860 // Form a mask of all bits from the lowest bit added through the top.
1861 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001862 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001863
1864 // See if the and mask includes all of these bits.
Reid Spencerb83eb642006-10-20 07:07:24 +00001865 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001866
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001867 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1868 // Okay, the xform is safe. Insert the new add pronto.
1869 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1870 LHS->getName()), I);
1871 return BinaryOperator::createAnd(NewAdd, C2);
1872 }
1873 }
1874 }
1875
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001876 // Try to fold constant add into select arguments.
1877 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001878 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001879 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001880 }
1881
Reid Spencer1628cec2006-10-26 06:15:43 +00001882 // add (cast *A to intptrtype) B ->
1883 // cast (GEP (cast *A to sbyte*) B) ->
1884 // intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00001885 {
Reid Spencer3da59db2006-11-27 01:05:10 +00001886 CastInst *CI = dyn_cast<CastInst>(LHS);
1887 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00001888 if (!CI) {
1889 CI = dyn_cast<CastInst>(RHS);
1890 Other = LHS;
1891 }
Andrew Lenharth45633262006-09-20 15:37:57 +00001892 if (CI && CI->getType()->isSized() &&
1893 (CI->getType()->getPrimitiveSize() ==
1894 TD->getIntPtrType()->getPrimitiveSize())
1895 && isa<PointerType>(CI->getOperand(0)->getType())) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001896 Value *I2 = InsertCastBefore(CI->getOperand(0),
Andrew Lenharth45633262006-09-20 15:37:57 +00001897 PointerType::get(Type::SByteTy), I);
1898 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00001899 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00001900 }
1901 }
1902
Chris Lattner7e708292002-06-25 16:13:24 +00001903 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001904}
1905
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001906// isSignBit - Return true if the value represented by the constant only has the
1907// highest order bit set.
1908static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001909 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00001910 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001911}
1912
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001913/// RemoveNoopCast - Strip off nonconverting casts from the value.
1914///
1915static Value *RemoveNoopCast(Value *V) {
1916 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1917 const Type *CTy = CI->getType();
1918 const Type *OpTy = CI->getOperand(0)->getType();
1919 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001920 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001921 return RemoveNoopCast(CI->getOperand(0));
1922 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1923 return RemoveNoopCast(CI->getOperand(0));
1924 }
1925 return V;
1926}
1927
Chris Lattner7e708292002-06-25 16:13:24 +00001928Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001929 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001930
Chris Lattner233f7dc2002-08-12 21:17:25 +00001931 if (Op0 == Op1) // sub X, X -> 0
1932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001933
Chris Lattner233f7dc2002-08-12 21:17:25 +00001934 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001935 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001936 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001937
Chris Lattnere87597f2004-10-16 18:11:37 +00001938 if (isa<UndefValue>(Op0))
1939 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1940 if (isa<UndefValue>(Op1))
1941 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1942
Chris Lattnerd65460f2003-11-05 01:06:05 +00001943 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1944 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001945 if (C->isAllOnesValue())
1946 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001947
Chris Lattnerd65460f2003-11-05 01:06:05 +00001948 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001949 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001950 if (match(Op1, m_Not(m_Value(X))))
1951 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001952 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001953 // -((uint)X >> 31) -> ((int)X >> 31)
1954 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001955 if (C->isNullValue()) {
1956 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1957 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Reid Spencer3822ff52006-11-08 06:47:33 +00001958 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001959 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001960 // Check to see if we are shifting out everything but the sign bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001961 if (CU->getZExtValue() ==
1962 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00001963 // Ok, the transformation is safe. Insert AShr.
1964 return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1965 CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00001966 }
1967 }
Reid Spencer3822ff52006-11-08 06:47:33 +00001968 }
1969 else if (SI->getOpcode() == Instruction::AShr) {
1970 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1971 // Check to see if we are shifting out everything but the sign bit.
1972 if (CU->getZExtValue() ==
1973 SI->getType()->getPrimitiveSizeInBits()-1) {
1974 // Ok, the transformation is safe. Insert LShr.
1975 return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1976 CU, SI->getName());
1977 }
1978 }
1979 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001980 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001981
1982 // Try to fold constant sub into select arguments.
1983 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001984 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001985 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001986
1987 if (isa<PHINode>(Op0))
1988 if (Instruction *NV = FoldOpIntoPhi(I))
1989 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001990 }
1991
Chris Lattner43d84d62005-04-07 16:15:25 +00001992 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1993 if (Op1I->getOpcode() == Instruction::Add &&
1994 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001995 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001996 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001997 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001998 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001999 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2000 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2001 // C1-(X+C2) --> (C1-C2)-X
2002 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2003 Op1I->getOperand(0));
2004 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002005 }
2006
Chris Lattnerfd059242003-10-15 16:48:29 +00002007 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002008 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2009 // is not used by anyone else...
2010 //
Chris Lattner0517e722004-02-02 20:09:56 +00002011 if (Op1I->getOpcode() == Instruction::Sub &&
2012 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002013 // Swap the two operands of the subexpr...
2014 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2015 Op1I->setOperand(0, IIOp1);
2016 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002017
Chris Lattnera2881962003-02-18 19:28:33 +00002018 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002019 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002020 }
2021
2022 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2023 //
2024 if (Op1I->getOpcode() == Instruction::And &&
2025 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2026 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2027
Chris Lattnerf523d062004-06-09 05:08:07 +00002028 Value *NewNot =
2029 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002030 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002031 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002032
Reid Spencerac5209e2006-10-16 23:08:08 +00002033 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002034 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002035 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Reid Spencer1628cec2006-10-26 06:15:43 +00002036 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00002037 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002038 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002039 ConstantExpr::getNeg(DivRHS));
2040
Chris Lattnerad3448c2003-02-18 19:57:07 +00002041 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002042 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002043 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002044 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00002045 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002046 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002047 }
Chris Lattner40371712002-05-09 01:29:19 +00002048 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002049 }
Chris Lattnera2881962003-02-18 19:28:33 +00002050
Chris Lattner7edc8c22005-04-07 17:14:51 +00002051 if (!Op0->getType()->isFloatingPoint())
2052 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2053 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002054 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2055 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2056 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2057 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002058 } else if (Op0I->getOpcode() == Instruction::Sub) {
2059 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2060 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002061 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002062
Chris Lattner50af16a2004-11-13 19:50:12 +00002063 ConstantInt *C1;
2064 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2065 if (X == Op1) { // X*C - X --> X * (C-1)
2066 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2067 return BinaryOperator::createMul(Op1, CP1);
2068 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002069
Chris Lattner50af16a2004-11-13 19:50:12 +00002070 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2071 if (X == dyn_castFoldableMul(Op1, C2))
2072 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2073 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002074 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002075}
2076
Chris Lattner4cb170c2004-02-23 06:38:22 +00002077/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2078/// really just returns true if the most significant (sign) bit is set.
2079static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2080 if (RHS->getType()->isSigned()) {
2081 // True if source is LHS < 0 or LHS <= -1
2082 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2083 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2084 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00002085 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002086 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2087 // the size of the integer type.
2088 if (Opcode == Instruction::SetGE)
Reid Spencerb83eb642006-10-20 07:07:24 +00002089 return RHSC->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002090 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002091 if (Opcode == Instruction::SetGT)
Reid Spencerb83eb642006-10-20 07:07:24 +00002092 return RHSC->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002093 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002094 }
2095 return false;
2096}
2097
Chris Lattner7e708292002-06-25 16:13:24 +00002098Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002099 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002100 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002101
Chris Lattnere87597f2004-10-16 18:11:37 +00002102 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2103 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2104
Chris Lattner233f7dc2002-08-12 21:17:25 +00002105 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002106 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2107 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002108
2109 // ((X << C1)*C2) == (X * (C2 << C1))
2110 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2111 if (SI->getOpcode() == Instruction::Shl)
2112 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002113 return BinaryOperator::createMul(SI->getOperand(0),
2114 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002115
Chris Lattner515c97c2003-09-11 22:24:54 +00002116 if (CI->isNullValue())
2117 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2118 if (CI->equalsInt(1)) // X * 1 == X
2119 return ReplaceInstUsesWith(I, Op0);
2120 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002121 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002122
Reid Spencerb83eb642006-10-20 07:07:24 +00002123 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002124 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2125 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00002126 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerb83eb642006-10-20 07:07:24 +00002127 ConstantInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002128 }
Robert Bocchino71698282004-07-27 21:02:21 +00002129 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002130 if (Op1F->isNullValue())
2131 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002132
Chris Lattnera2881962003-02-18 19:28:33 +00002133 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2134 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2135 if (Op1F->getValue() == 1.0)
2136 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2137 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002138
2139 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2140 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2141 isa<ConstantInt>(Op0I->getOperand(1))) {
2142 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2143 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2144 Op1, "tmp");
2145 InsertNewInstBefore(Add, I);
2146 Value *C1C2 = ConstantExpr::getMul(Op1,
2147 cast<Constant>(Op0I->getOperand(1)));
2148 return BinaryOperator::createAdd(Add, C1C2);
2149
2150 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002151
2152 // Try to fold constant mul into select arguments.
2153 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002154 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002155 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002156
2157 if (isa<PHINode>(Op0))
2158 if (Instruction *NV = FoldOpIntoPhi(I))
2159 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002160 }
2161
Chris Lattnera4f445b2003-03-10 23:23:04 +00002162 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2163 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002164 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002165
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002166 // If one of the operands of the multiply is a cast from a boolean value, then
2167 // we know the bool is either zero or one, so this is a 'masking' multiply.
2168 // See if we can simplify things based on how the boolean was originally
2169 // formed.
2170 CastInst *BoolCast = 0;
2171 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2172 if (CI->getOperand(0)->getType() == Type::BoolTy)
2173 BoolCast = CI;
2174 if (!BoolCast)
2175 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2176 if (CI->getOperand(0)->getType() == Type::BoolTy)
2177 BoolCast = CI;
2178 if (BoolCast) {
2179 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2180 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2181 const Type *SCOpTy = SCIOp0->getType();
2182
Chris Lattner4cb170c2004-02-23 06:38:22 +00002183 // If the setcc is true iff the sign bit of X is set, then convert this
2184 // multiply into a shift/and combination.
2185 if (isa<ConstantInt>(SCIOp1) &&
2186 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002187 // Shift the X value right to turn it into "all signbits".
Reid Spencerb83eb642006-10-20 07:07:24 +00002188 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00002189 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002190 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002191 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Reid Spencer811b0cb2006-10-26 19:19:06 +00002192 SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002193 }
2194
2195 Value *V =
Reid Spencer3822ff52006-11-08 06:47:33 +00002196 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002197 BoolCast->getOperand(0)->getName()+
2198 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002199
2200 // If the multiply type is not the same as the source type, sign extend
2201 // or truncate to the multiply type.
2202 if (I.getType() != V->getType())
Reid Spencer811b0cb2006-10-26 19:19:06 +00002203 V = InsertCastBefore(V, I.getType(), I);
Misha Brukmanfd939082005-04-21 23:48:37 +00002204
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002205 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002206 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002207 }
2208 }
2209 }
2210
Chris Lattner7e708292002-06-25 16:13:24 +00002211 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002212}
2213
Reid Spencer1628cec2006-10-26 06:15:43 +00002214/// This function implements the transforms on div instructions that work
2215/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2216/// used by the visitors to those instructions.
2217/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002218Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002219 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002220
Reid Spencer1628cec2006-10-26 06:15:43 +00002221 // undef / X -> 0
2222 if (isa<UndefValue>(Op0))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002223 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002224
2225 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002226 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002227 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002228
Reid Spencer1628cec2006-10-26 06:15:43 +00002229 // Handle cases involving: div X, (select Cond, Y, Z)
Chris Lattner8e49e082006-09-09 20:26:32 +00002230 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2231 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
Reid Spencer1628cec2006-10-26 06:15:43 +00002232 // same basic block, then we replace the select with Y, and the condition
2233 // of the select with false (if the cond value is in the same BB). If the
Chris Lattner8e49e082006-09-09 20:26:32 +00002234 // select has uses other than the div, this allows them to be simplified
Reid Spencer1628cec2006-10-26 06:15:43 +00002235 // also. Note that div X, Y is just as good as div X, 0 (undef)
Chris Lattner8e49e082006-09-09 20:26:32 +00002236 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2237 if (ST->isNullValue()) {
2238 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2239 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002240 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002241 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2242 I.setOperand(1, SI->getOperand(2));
2243 else
2244 UpdateValueUsesWith(SI, SI->getOperand(2));
2245 return &I;
2246 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002247
Chris Lattner8e49e082006-09-09 20:26:32 +00002248 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2249 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2250 if (ST->isNullValue()) {
2251 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2252 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002253 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002254 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2255 I.setOperand(1, SI->getOperand(1));
2256 else
2257 UpdateValueUsesWith(SI, SI->getOperand(1));
2258 return &I;
2259 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002260 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002261
Reid Spencer1628cec2006-10-26 06:15:43 +00002262 return 0;
2263}
Misha Brukmanfd939082005-04-21 23:48:37 +00002264
Reid Spencer1628cec2006-10-26 06:15:43 +00002265/// This function implements the transforms common to both integer division
2266/// instructions (udiv and sdiv). It is called by the visitors to those integer
2267/// division instructions.
2268/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002269Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002270 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2271
2272 if (Instruction *Common = commonDivTransforms(I))
2273 return Common;
2274
2275 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2276 // div X, 1 == X
2277 if (RHS->equalsInt(1))
2278 return ReplaceInstUsesWith(I, Op0);
2279
2280 // (X / C1) / C2 -> X / (C1*C2)
2281 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2282 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2283 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2284 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2285 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002286 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002287
2288 if (!RHS->isNullValue()) { // avoid X udiv 0
2289 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2290 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2291 return R;
2292 if (isa<PHINode>(Op0))
2293 if (Instruction *NV = FoldOpIntoPhi(I))
2294 return NV;
2295 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002296 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002297
Chris Lattnera2881962003-02-18 19:28:33 +00002298 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002299 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002300 if (LHS->equalsInt(0))
2301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2302
Reid Spencer1628cec2006-10-26 06:15:43 +00002303 return 0;
2304}
2305
2306Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2307 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2308
2309 // Handle the integer div common cases
2310 if (Instruction *Common = commonIDivTransforms(I))
2311 return Common;
2312
2313 // X udiv C^2 -> X >> C
2314 // Check to see if this is an unsigned division with an exact power of 2,
2315 // if so, convert to a right shift.
2316 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2317 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2318 if (isPowerOf2_64(Val)) {
2319 uint64_t ShiftAmt = Log2_64(Val);
Reid Spencer3822ff52006-11-08 06:47:33 +00002320 return new ShiftInst(Instruction::LShr, Op0,
2321 ConstantInt::get(Type::UByteTy, ShiftAmt));
Reid Spencer1628cec2006-10-26 06:15:43 +00002322 }
2323 }
2324
2325 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2326 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2327 if (RHSI->getOpcode() == Instruction::Shl &&
2328 isa<ConstantInt>(RHSI->getOperand(0))) {
2329 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2330 if (isPowerOf2_64(C1)) {
2331 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002332 const Type *NTy = N->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00002333 if (uint64_t C2 = Log2_64(C1)) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002334 Constant *C2V = ConstantInt::get(NTy, C2);
2335 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002336 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002337 return new ShiftInst(Instruction::LShr, Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002338 }
2339 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002340 }
2341
Reid Spencer1628cec2006-10-26 06:15:43 +00002342 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2343 // where C1&C2 are powers of two.
2344 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2345 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2346 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2347 if (!STO->isNullValue() && !STO->isNullValue()) {
2348 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2349 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2350 // Compute the shift amounts
2351 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Reid Spencer1628cec2006-10-26 06:15:43 +00002352 // Construct the "on true" case of the select
2353 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2354 Instruction *TSI =
Reid Spencer3822ff52006-11-08 06:47:33 +00002355 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
Reid Spencer1628cec2006-10-26 06:15:43 +00002356 TSI = InsertNewInstBefore(TSI, I);
2357
2358 // Construct the "on false" case of the select
2359 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2360 Instruction *FSI =
Reid Spencer3822ff52006-11-08 06:47:33 +00002361 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00002362 FSI = InsertNewInstBefore(FSI, I);
2363
2364 // construct the select instruction and return it.
Reid Spencer3822ff52006-11-08 06:47:33 +00002365 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002366 }
2367 }
2368 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002369 return 0;
2370}
2371
Reid Spencer1628cec2006-10-26 06:15:43 +00002372Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2374
2375 // Handle the integer div common cases
2376 if (Instruction *Common = commonIDivTransforms(I))
2377 return Common;
2378
2379 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2380 // sdiv X, -1 == -X
2381 if (RHS->isAllOnesValue())
2382 return BinaryOperator::createNeg(Op0);
2383
2384 // -X/C -> X/-C
2385 if (Value *LHSNeg = dyn_castNegVal(Op0))
2386 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2387 }
2388
2389 // If the sign bits of both operands are zero (i.e. we can prove they are
2390 // unsigned inputs), turn this into a udiv.
2391 if (I.getType()->isInteger()) {
2392 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2393 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2394 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2395 }
2396 }
2397
2398 return 0;
2399}
2400
2401Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2402 return commonDivTransforms(I);
2403}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002404
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002405/// GetFactor - If we can prove that the specified value is at least a multiple
2406/// of some factor, return that factor.
2407static Constant *GetFactor(Value *V) {
2408 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2409 return CI;
2410
2411 // Unless we can be tricky, we know this is a multiple of 1.
2412 Constant *Result = ConstantInt::get(V->getType(), 1);
2413
2414 Instruction *I = dyn_cast<Instruction>(V);
2415 if (!I) return Result;
2416
2417 if (I->getOpcode() == Instruction::Mul) {
2418 // Handle multiplies by a constant, etc.
2419 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2420 GetFactor(I->getOperand(1)));
2421 } else if (I->getOpcode() == Instruction::Shl) {
2422 // (X<<C) -> X * (1 << C)
2423 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2424 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2425 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2426 }
2427 } else if (I->getOpcode() == Instruction::And) {
2428 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2429 // X & 0xFFF0 is known to be a multiple of 16.
2430 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2431 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2432 return ConstantExpr::getShl(Result,
Reid Spencerb83eb642006-10-20 07:07:24 +00002433 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002434 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002435 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002436 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002437 if (!CI->isIntegerCast())
2438 return Result;
2439 Value *Op = CI->getOperand(0);
2440 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002441 }
2442 return Result;
2443}
2444
Reid Spencer0a783f72006-11-02 01:53:59 +00002445/// This function implements the transforms on rem instructions that work
2446/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2447/// is used by the visitors to those instructions.
2448/// @brief Transforms common to all three rem instructions
2449Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002450 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002451
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002452 // 0 % X == 0, we don't need to preserve faults!
2453 if (Constant *LHS = dyn_cast<Constant>(Op0))
2454 if (LHS->isNullValue())
2455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2456
2457 if (isa<UndefValue>(Op0)) // undef % X -> 0
2458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2459 if (isa<UndefValue>(Op1))
2460 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002461
2462 // Handle cases involving: rem X, (select Cond, Y, Z)
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2464 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2465 // the same basic block, then we replace the select with Y, and the
2466 // condition of the select with false (if the cond value is in the same
2467 // BB). If the select has uses other than the div, this allows them to be
2468 // simplified also.
2469 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2470 if (ST->isNullValue()) {
2471 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2472 if (CondI && CondI->getParent() == I.getParent())
2473 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2474 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2475 I.setOperand(1, SI->getOperand(2));
2476 else
2477 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002478 return &I;
2479 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002480 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2481 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2482 if (ST->isNullValue()) {
2483 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2484 if (CondI && CondI->getParent() == I.getParent())
2485 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2486 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2487 I.setOperand(1, SI->getOperand(1));
2488 else
2489 UpdateValueUsesWith(SI, SI->getOperand(1));
2490 return &I;
2491 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002492 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002493
Reid Spencer0a783f72006-11-02 01:53:59 +00002494 return 0;
2495}
2496
2497/// This function implements the transforms common to both integer remainder
2498/// instructions (urem and srem). It is called by the visitors to those integer
2499/// remainder instructions.
2500/// @brief Common integer remainder transforms
2501Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2503
2504 if (Instruction *common = commonRemTransforms(I))
2505 return common;
2506
Chris Lattner857e8cd2004-12-12 21:48:58 +00002507 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002508 // X % 0 == undef, we don't need to preserve faults!
2509 if (RHS->equalsInt(0))
2510 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2511
Chris Lattnera2881962003-02-18 19:28:33 +00002512 if (RHS->equalsInt(1)) // X % 1 == 0
2513 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2514
Chris Lattner97943922006-02-28 05:49:21 +00002515 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2516 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2517 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2518 return R;
2519 } else if (isa<PHINode>(Op0I)) {
2520 if (Instruction *NV = FoldOpIntoPhi(I))
2521 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002522 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002523 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2524 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002525 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002526 }
Chris Lattnera2881962003-02-18 19:28:33 +00002527 }
2528
Reid Spencer0a783f72006-11-02 01:53:59 +00002529 return 0;
2530}
2531
2532Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2534
2535 if (Instruction *common = commonIRemTransforms(I))
2536 return common;
2537
2538 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2539 // X urem C^2 -> X and C
2540 // Check to see if this is an unsigned remainder with an exact power of 2,
2541 // if so, convert to a bitwise and.
2542 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2543 if (isPowerOf2_64(C->getZExtValue()))
2544 return BinaryOperator::createAnd(Op0, SubOne(C));
2545 }
2546
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002547 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002548 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2549 if (RHSI->getOpcode() == Instruction::Shl &&
2550 isa<ConstantInt>(RHSI->getOperand(0))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002551 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002552 if (isPowerOf2_64(C1)) {
2553 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2554 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2555 "tmp"), I);
2556 return BinaryOperator::createAnd(Op0, Add);
2557 }
2558 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002559 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002560
Reid Spencer0a783f72006-11-02 01:53:59 +00002561 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2562 // where C1&C2 are powers of two.
2563 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2564 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2565 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2566 // STO == 0 and SFO == 0 handled above.
2567 if (isPowerOf2_64(STO->getZExtValue()) &&
2568 isPowerOf2_64(SFO->getZExtValue())) {
2569 Value *TrueAnd = InsertNewInstBefore(
2570 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2571 Value *FalseAnd = InsertNewInstBefore(
2572 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2573 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2574 }
2575 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002576 }
2577
Chris Lattner3f5b8772002-05-06 16:14:14 +00002578 return 0;
2579}
2580
Reid Spencer0a783f72006-11-02 01:53:59 +00002581Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2582 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2583
2584 if (Instruction *common = commonIRemTransforms(I))
2585 return common;
2586
2587 if (Value *RHSNeg = dyn_castNegVal(Op1))
2588 if (!isa<ConstantInt>(RHSNeg) ||
2589 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2590 // X % -Y -> X % Y
2591 AddUsesToWorkList(I);
2592 I.setOperand(1, RHSNeg);
2593 return &I;
2594 }
2595
2596 // If the top bits of both operands are zero (i.e. we can prove they are
2597 // unsigned inputs), turn this into a urem.
2598 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2599 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2600 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2601 return BinaryOperator::createURem(Op0, Op1, I.getName());
2602 }
2603
2604 return 0;
2605}
2606
2607Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002608 return commonRemTransforms(I);
2609}
2610
Chris Lattner8b170942002-08-09 23:47:40 +00002611// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002612static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002613 if (C->getType()->isUnsigned())
2614 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002615
Chris Lattner8b170942002-08-09 23:47:40 +00002616 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00002617 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002618 int64_t Val = INT64_MAX; // All ones
2619 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencerb83eb642006-10-20 07:07:24 +00002620 return C->getSExtValue() == Val-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002621}
2622
2623// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002624static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002625 if (C->getType()->isUnsigned())
2626 return C->getZExtValue() == 1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002627
2628 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00002629 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002630 int64_t Val = -1; // All ones
2631 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencerb83eb642006-10-20 07:07:24 +00002632 return C->getSExtValue() == Val+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002633}
2634
Chris Lattner457dd822004-06-09 07:59:58 +00002635// isOneBitSet - Return true if there is exactly one bit set in the specified
2636// constant.
2637static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002638 uint64_t V = CI->getZExtValue();
Chris Lattner457dd822004-06-09 07:59:58 +00002639 return V && (V & (V-1)) == 0;
2640}
2641
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002642#if 0 // Currently unused
2643// isLowOnes - Return true if the constant is of the form 0+1+.
2644static bool isLowOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002645 uint64_t V = CI->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002646
2647 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002648 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002649
2650 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2651 return U && V && (U & V) == 0;
2652}
2653#endif
2654
2655// isHighOnes - Return true if the constant is of the form 1+0+.
2656// This is the same as lowones(~X).
2657static bool isHighOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002658 uint64_t V = ~CI->getZExtValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002659 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002660
2661 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002662 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002663
2664 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2665 return U && V && (U & V) == 0;
2666}
2667
2668
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002669/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2670/// are carefully arranged to allow folding of expressions such as:
2671///
2672/// (A < B) | (A > B) --> (A != B)
2673///
2674/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2675/// represents that the comparison is true if A == B, and bit value '1' is true
2676/// if A < B.
2677///
2678static unsigned getSetCondCode(const SetCondInst *SCI) {
2679 switch (SCI->getOpcode()) {
2680 // False -> 0
2681 case Instruction::SetGT: return 1;
2682 case Instruction::SetEQ: return 2;
2683 case Instruction::SetGE: return 3;
2684 case Instruction::SetLT: return 4;
2685 case Instruction::SetNE: return 5;
2686 case Instruction::SetLE: return 6;
2687 // True -> 7
2688 default:
2689 assert(0 && "Invalid SetCC opcode!");
2690 return 0;
2691 }
2692}
2693
2694/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2695/// opcode and two operands into either a constant true or false, or a brand new
2696/// SetCC instruction.
2697static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2698 switch (Opcode) {
Chris Lattner47811b72006-09-28 23:35:22 +00002699 case 0: return ConstantBool::getFalse();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002700 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2701 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2702 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2703 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2704 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2705 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner47811b72006-09-28 23:35:22 +00002706 case 7: return ConstantBool::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002707 default: assert(0 && "Illegal SetCCCode!"); return 0;
2708 }
2709}
2710
2711// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002712namespace {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002713struct FoldSetCCLogical {
2714 InstCombiner &IC;
2715 Value *LHS, *RHS;
2716 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2717 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2718 bool shouldApply(Value *V) const {
2719 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2720 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2721 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2722 return false;
2723 }
2724 Instruction *apply(BinaryOperator &Log) const {
2725 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2726 if (SCI->getOperand(0) != LHS) {
2727 assert(SCI->getOperand(1) == LHS);
2728 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2729 }
2730
2731 unsigned LHSCode = getSetCondCode(SCI);
2732 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2733 unsigned Code;
2734 switch (Log.getOpcode()) {
2735 case Instruction::And: Code = LHSCode & RHSCode; break;
2736 case Instruction::Or: Code = LHSCode | RHSCode; break;
2737 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002738 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002739 }
2740
2741 Value *RV = getSetCCValue(Code, LHS, RHS);
2742 if (Instruction *I = dyn_cast<Instruction>(RV))
2743 return I;
2744 // Otherwise, it's a constant boolean value...
2745 return IC.ReplaceInstUsesWith(Log, RV);
2746 }
2747};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00002748} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002749
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002750// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2751// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2752// guaranteed to be either a shift instruction or a binary operator.
2753Instruction *InstCombiner::OptAndOp(Instruction *Op,
2754 ConstantIntegral *OpRHS,
2755 ConstantIntegral *AndRHS,
2756 BinaryOperator &TheAnd) {
2757 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002758 Constant *Together = 0;
2759 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002760 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002761
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002762 switch (Op->getOpcode()) {
2763 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002764 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002765 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2766 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002767 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002768 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002769 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002770 }
2771 break;
2772 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002773 if (Together == AndRHS) // (X | C) & C --> C
2774 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002775
Chris Lattner6e7ba452005-01-01 16:22:27 +00002776 if (Op->hasOneUse() && Together != OpRHS) {
2777 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2778 std::string Op0Name = Op->getName(); Op->setName("");
2779 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2780 InsertNewInstBefore(Or, TheAnd);
2781 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002782 }
2783 break;
2784 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002785 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002786 // Adding a one to a single bit bit-field should be turned into an XOR
2787 // of the bit. First thing to check is to see if this AND is with a
2788 // single bit constant.
Reid Spencerb83eb642006-10-20 07:07:24 +00002789 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002790
2791 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002792 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002793
2794 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002795 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002796 // Ok, at this point, we know that we are masking the result of the
2797 // ADD down to exactly one bit. If the constant we are adding has
2798 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencerb83eb642006-10-20 07:07:24 +00002799 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002800
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002801 // Check to see if any bits below the one bit set in AndRHSV are set.
2802 if ((AddRHS & (AndRHSV-1)) == 0) {
2803 // If not, the only thing that can effect the output of the AND is
2804 // the bit specified by AndRHSV. If that bit is set, the effect of
2805 // the XOR is to toggle the bit. If it is clear, then the ADD has
2806 // no effect.
2807 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2808 TheAnd.setOperand(0, X);
2809 return &TheAnd;
2810 } else {
2811 std::string Name = Op->getName(); Op->setName("");
2812 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002813 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002814 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002815 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002816 }
2817 }
2818 }
2819 }
2820 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002821
2822 case Instruction::Shl: {
2823 // We know that the AND will not produce any of the bits shifted in, so if
2824 // the anded constant includes them, clear them now!
2825 //
2826 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002827 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2828 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002829
Chris Lattner0c967662004-09-24 15:21:34 +00002830 if (CI == ShlMask) { // Masking out bits that the shift already masks
2831 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2832 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002833 TheAnd.setOperand(1, CI);
2834 return &TheAnd;
2835 }
2836 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002837 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002838 case Instruction::LShr:
2839 {
Chris Lattner62a355c2003-09-19 19:05:02 +00002840 // We know that the AND will not produce any of the bits shifted in, so if
2841 // the anded constant includes them, clear them now! This only applies to
2842 // unsigned shifts, because a signed shr may bring in set bits!
2843 //
Reid Spencer3822ff52006-11-08 06:47:33 +00002844 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2845 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2846 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00002847
Reid Spencer3822ff52006-11-08 06:47:33 +00002848 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2849 return ReplaceInstUsesWith(TheAnd, Op);
2850 } else if (CI != AndRHS) {
2851 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2852 return &TheAnd;
2853 }
2854 break;
2855 }
2856 case Instruction::AShr:
2857 // Signed shr.
2858 // See if this is shifting in some sign extension, then masking it out
2859 // with an and.
2860 if (Op->hasOneUse()) {
2861 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2862 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2863 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2864 if (CI == AndRHS) { // Masking out bits shifted in.
2865 // Make the argument unsigned.
2866 Value *ShVal = Op->getOperand(0);
2867 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2868 OpRHS, Op->getName()),
2869 TheAnd);
2870 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2871 return BinaryOperator::createAnd(ShVal, AndRHS2, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00002872 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002873 }
2874 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002875 }
2876 return 0;
2877}
2878
Chris Lattner8b170942002-08-09 23:47:40 +00002879
Chris Lattnera96879a2004-09-29 17:40:11 +00002880/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2881/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2882/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2883/// insert new instructions.
2884Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2885 bool Inside, Instruction &IB) {
2886 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2887 "Lo is not <= Hi in range emission code!");
2888 if (Inside) {
2889 if (Lo == Hi) // Trivially false.
2890 return new SetCondInst(Instruction::SetNE, V, V);
2891 if (cast<ConstantIntegral>(Lo)->isMinValue())
2892 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002893
Chris Lattnera96879a2004-09-29 17:40:11 +00002894 Constant *AddCST = ConstantExpr::getNeg(Lo);
2895 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2896 InsertNewInstBefore(Add, IB);
2897 // Convert to unsigned for the comparison.
2898 const Type *UnsType = Add->getType()->getUnsignedVersion();
2899 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2900 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2901 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2902 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2903 }
2904
2905 if (Lo == Hi) // Trivially true.
2906 return new SetCondInst(Instruction::SetEQ, V, V);
2907
2908 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencerb83eb642006-10-20 07:07:24 +00002909
2910 // V < 0 || V >= Hi ->'V > Hi-1'
2911 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattnera96879a2004-09-29 17:40:11 +00002912 return new SetCondInst(Instruction::SetGT, V, Hi);
2913
2914 // Emit X-Lo > Hi-Lo-1
2915 Constant *AddCST = ConstantExpr::getNeg(Lo);
2916 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2917 InsertNewInstBefore(Add, IB);
2918 // Convert to unsigned for the comparison.
2919 const Type *UnsType = Add->getType()->getUnsignedVersion();
2920 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2921 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2922 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2923 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2924}
2925
Chris Lattner7203e152005-09-18 07:22:02 +00002926// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2927// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2928// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2929// not, since all 1s are not contiguous.
2930static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002931 uint64_t V = Val->getZExtValue();
Chris Lattner7203e152005-09-18 07:22:02 +00002932 if (!isShiftedMask_64(V)) return false;
2933
2934 // look for the first zero bit after the run of ones
2935 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2936 // look for the first non-zero bit
2937 ME = 64-CountLeadingZeros_64(V);
2938 return true;
2939}
2940
2941
2942
2943/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2944/// where isSub determines whether the operator is a sub. If we can fold one of
2945/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002946///
2947/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2948/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2949/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2950///
2951/// return (A +/- B).
2952///
2953Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2954 ConstantIntegral *Mask, bool isSub,
2955 Instruction &I) {
2956 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2957 if (!LHSI || LHSI->getNumOperands() != 2 ||
2958 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2959
2960 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2961
2962 switch (LHSI->getOpcode()) {
2963 default: return 0;
2964 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002965 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2966 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencerb83eb642006-10-20 07:07:24 +00002967 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattner7203e152005-09-18 07:22:02 +00002968 break;
2969
2970 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2971 // part, we don't need any explicit masks to take them out of A. If that
2972 // is all N is, ignore it.
2973 unsigned MB, ME;
2974 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002975 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2976 Mask >>= 64-MB+1;
2977 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002978 break;
2979 }
2980 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002981 return 0;
2982 case Instruction::Or:
2983 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002984 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencerb83eb642006-10-20 07:07:24 +00002985 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattner7203e152005-09-18 07:22:02 +00002986 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002987 break;
2988 return 0;
2989 }
2990
2991 Instruction *New;
2992 if (isSub)
2993 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2994 else
2995 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2996 return InsertNewInstBefore(New, I);
2997}
2998
Chris Lattner7e708292002-06-25 16:13:24 +00002999Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003000 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003002
Chris Lattnere87597f2004-10-16 18:11:37 +00003003 if (isa<UndefValue>(Op1)) // X & undef -> 0
3004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3005
Chris Lattner6e7ba452005-01-01 16:22:27 +00003006 // and X, X = X
3007 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003008 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003009
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003010 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003011 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00003012 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003013 if (!isa<PackedType>(I.getType()) &&
3014 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00003015 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00003016 return &I;
3017
Chris Lattner6e7ba452005-01-01 16:22:27 +00003018 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00003019 uint64_t AndRHSMask = AndRHS->getZExtValue();
3020 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00003021 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003022
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003023 // Optimize a variety of ((val OP C1) & C2) combinations...
3024 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3025 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003026 Value *Op0LHS = Op0I->getOperand(0);
3027 Value *Op0RHS = Op0I->getOperand(1);
3028 switch (Op0I->getOpcode()) {
3029 case Instruction::Xor:
3030 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003031 // If the mask is only needed on one incoming arm, push it up.
3032 if (Op0I->hasOneUse()) {
3033 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3034 // Not masking anything out for the LHS, move to RHS.
3035 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3036 Op0RHS->getName()+".masked");
3037 InsertNewInstBefore(NewRHS, I);
3038 return BinaryOperator::create(
3039 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003040 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003041 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003042 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3043 // Not masking anything out for the RHS, move to LHS.
3044 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3045 Op0LHS->getName()+".masked");
3046 InsertNewInstBefore(NewLHS, I);
3047 return BinaryOperator::create(
3048 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3049 }
3050 }
3051
Chris Lattner6e7ba452005-01-01 16:22:27 +00003052 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003053 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003054 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3055 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3056 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3057 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3058 return BinaryOperator::createAnd(V, AndRHS);
3059 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3060 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003061 break;
3062
3063 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003064 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3065 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3066 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3067 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3068 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003069 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003070 }
3071
Chris Lattner58403262003-07-23 19:25:52 +00003072 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003073 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003074 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003075 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003076 // If this is an integer truncation or change from signed-to-unsigned, and
3077 // if the source is an and/or with immediate, transform it. This
3078 // frequently occurs for bitfield accesses.
3079 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003080 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003081 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00003082 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00003083 if (CastOp->getOpcode() == Instruction::And) {
3084 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003085 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3086 // This will fold the two constants together, which may allow
3087 // other simplifications.
Chris Lattner2b83af22005-08-07 07:03:10 +00003088 Instruction *NewCast =
Reid Spencer3da59db2006-11-27 01:05:10 +00003089 CastInst::createInferredCast(CastOp->getOperand(0), I.getType(),
Chris Lattner2b83af22005-08-07 07:03:10 +00003090 CastOp->getName()+".shrunk");
3091 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003092 // trunc_or_bitcast(C1)&C2
3093 Instruction::CastOps opc = (
3094 AndCI->getType()->getPrimitiveSizeInBits() ==
3095 I.getType()->getPrimitiveSizeInBits() ?
3096 Instruction::BitCast : Instruction::Trunc);
3097 Constant *C3 = ConstantExpr::getCast(opc, AndCI, I.getType());
3098 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003099 return BinaryOperator::createAnd(NewCast, C3);
3100 } else if (CastOp->getOpcode() == Instruction::Or) {
3101 // Change: and (cast (or X, C1) to T), C2
3102 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003103 Constant *C3 = ConstantExpr::getCast(AndCI, I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003104 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3105 return ReplaceInstUsesWith(I, AndRHS);
3106 }
3107 }
Chris Lattner06782f82003-07-23 19:36:21 +00003108 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003109
3110 // Try to fold constant and into select arguments.
3111 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003112 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003113 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003114 if (isa<PHINode>(Op0))
3115 if (Instruction *NV = FoldOpIntoPhi(I))
3116 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003117 }
3118
Chris Lattner8d969642003-03-10 23:06:50 +00003119 Value *Op0NotVal = dyn_castNotVal(Op0);
3120 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003121
Chris Lattner5b62aa72004-06-18 06:07:51 +00003122 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3124
Misha Brukmancb6267b2004-07-30 12:50:08 +00003125 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003126 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003127 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3128 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003129 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003130 return BinaryOperator::createNot(Or);
3131 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003132
3133 {
3134 Value *A = 0, *B = 0;
Chris Lattner2082ad92006-02-13 23:07:23 +00003135 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3136 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3137 return ReplaceInstUsesWith(I, Op1);
3138 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3139 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3140 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00003141
3142 if (Op0->hasOneUse() &&
3143 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3144 if (A == Op1) { // (A^B)&A -> A&(A^B)
3145 I.swapOperands(); // Simplify below
3146 std::swap(Op0, Op1);
3147 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3148 cast<BinaryOperator>(Op0)->swapOperands();
3149 I.swapOperands(); // Simplify below
3150 std::swap(Op0, Op1);
3151 }
3152 }
3153 if (Op1->hasOneUse() &&
3154 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3155 if (B == Op0) { // B&(A^B) -> B&(B^A)
3156 cast<BinaryOperator>(Op1)->swapOperands();
3157 std::swap(A, B);
3158 }
3159 if (A == Op0) { // A&(A^B) -> A & ~B
3160 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3161 InsertNewInstBefore(NotB, I);
3162 return BinaryOperator::createAnd(A, NotB);
3163 }
3164 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003165 }
3166
Chris Lattnera2881962003-02-18 19:28:33 +00003167
Chris Lattner955f3312004-09-28 21:48:02 +00003168 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3169 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003170 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3171 return R;
3172
Chris Lattner955f3312004-09-28 21:48:02 +00003173 Value *LHSVal, *RHSVal;
3174 ConstantInt *LHSCst, *RHSCst;
3175 Instruction::BinaryOps LHSCC, RHSCC;
3176 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3177 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3178 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3179 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00003180 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00003181 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3182 // Ensure that the larger constant is on the RHS.
3183 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3184 SetCondInst *LHS = cast<SetCondInst>(Op0);
3185 if (cast<ConstantBool>(Cmp)->getValue()) {
3186 std::swap(LHS, RHS);
3187 std::swap(LHSCst, RHSCst);
3188 std::swap(LHSCC, RHSCC);
3189 }
3190
3191 // At this point, we know we have have two setcc instructions
3192 // comparing a value against two constants and and'ing the result
3193 // together. Because of the above check, we know that we only have
3194 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3195 // FoldSetCCLogical check above), that the two constants are not
3196 // equal.
3197 assert(LHSCst != RHSCst && "Compares not folded above?");
3198
3199 switch (LHSCC) {
3200 default: assert(0 && "Unknown integer condition code!");
3201 case Instruction::SetEQ:
3202 switch (RHSCC) {
3203 default: assert(0 && "Unknown integer condition code!");
3204 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3205 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003206 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner955f3312004-09-28 21:48:02 +00003207 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3208 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3209 return ReplaceInstUsesWith(I, LHS);
3210 }
3211 case Instruction::SetNE:
3212 switch (RHSCC) {
3213 default: assert(0 && "Unknown integer condition code!");
3214 case Instruction::SetLT:
3215 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3216 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3217 break; // (X != 13 & X < 15) -> no change
3218 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3219 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3220 return ReplaceInstUsesWith(I, RHS);
3221 case Instruction::SetNE:
3222 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3223 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3224 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3225 LHSVal->getName()+".off");
3226 InsertNewInstBefore(Add, I);
3227 const Type *UnsType = Add->getType()->getUnsignedVersion();
3228 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3229 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3230 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3231 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3232 }
3233 break; // (X != 13 & X != 15) -> no change
3234 }
3235 break;
3236 case Instruction::SetLT:
3237 switch (RHSCC) {
3238 default: assert(0 && "Unknown integer condition code!");
3239 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3240 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003241 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner955f3312004-09-28 21:48:02 +00003242 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3243 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3244 return ReplaceInstUsesWith(I, LHS);
3245 }
3246 case Instruction::SetGT:
3247 switch (RHSCC) {
3248 default: assert(0 && "Unknown integer condition code!");
3249 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3250 return ReplaceInstUsesWith(I, LHS);
3251 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3252 return ReplaceInstUsesWith(I, RHS);
3253 case Instruction::SetNE:
3254 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3255 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3256 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00003257 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3258 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00003259 }
3260 }
3261 }
3262 }
3263
Chris Lattner6fc205f2006-05-05 06:39:07 +00003264 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Chris Lattnere511b742006-11-14 07:46:50 +00003265 if (CastInst *Op1C = dyn_cast<CastInst>(Op1)) {
3266 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3267 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner581a7ad2006-05-05 20:51:30 +00003268 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003269 // Only do this if the casts both really cause code to be generated.
3270 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3271 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003272 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3273 Op1C->getOperand(0),
3274 I.getName());
3275 InsertNewInstBefore(NewOp, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003276 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner6fc205f2006-05-05 06:39:07 +00003277 }
Chris Lattnere511b742006-11-14 07:46:50 +00003278 }
3279 }
3280
3281 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3282 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3283 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3284 if (SI0->getOpcode() == SI1->getOpcode() &&
3285 SI0->getOperand(1) == SI1->getOperand(1) &&
3286 (SI0->hasOneUse() || SI1->hasOneUse())) {
3287 Instruction *NewOp =
3288 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3289 SI1->getOperand(0),
3290 SI0->getName()), I);
3291 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3292 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003293 }
3294
Chris Lattner7e708292002-06-25 16:13:24 +00003295 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003296}
3297
Chris Lattnerafe91a52006-06-15 19:07:26 +00003298/// CollectBSwapParts - Look to see if the specified value defines a single byte
3299/// in the result. If it does, and if the specified byte hasn't been filled in
3300/// yet, fill it in and return false.
3301static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3302 Instruction *I = dyn_cast<Instruction>(V);
3303 if (I == 0) return true;
3304
3305 // If this is an or instruction, it is an inner node of the bswap.
3306 if (I->getOpcode() == Instruction::Or)
3307 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3308 CollectBSwapParts(I->getOperand(1), ByteValues);
3309
3310 // If this is a shift by a constant int, and it is "24", then its operand
3311 // defines a byte. We only handle unsigned types here.
3312 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3313 // Not shifting the entire input by N-1 bytes?
Reid Spencerb83eb642006-10-20 07:07:24 +00003314 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003315 8*(ByteValues.size()-1))
3316 return true;
3317
3318 unsigned DestNo;
3319 if (I->getOpcode() == Instruction::Shl) {
3320 // X << 24 defines the top byte with the lowest of the input bytes.
3321 DestNo = ByteValues.size()-1;
3322 } else {
3323 // X >>u 24 defines the low byte with the highest of the input bytes.
3324 DestNo = 0;
3325 }
3326
3327 // If the destination byte value is already defined, the values are or'd
3328 // together, which isn't a bswap (unless it's an or of the same bits).
3329 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3330 return true;
3331 ByteValues[DestNo] = I->getOperand(0);
3332 return false;
3333 }
3334
3335 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3336 // don't have this.
3337 Value *Shift = 0, *ShiftLHS = 0;
3338 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3339 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3340 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3341 return true;
3342 Instruction *SI = cast<Instruction>(Shift);
3343
3344 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencerb83eb642006-10-20 07:07:24 +00003345 if (ShiftAmt->getZExtValue() & 7 ||
3346 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003347 return true;
3348
3349 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3350 unsigned DestByte;
3351 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencerb83eb642006-10-20 07:07:24 +00003352 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003353 break;
3354 // Unknown mask for bswap.
3355 if (DestByte == ByteValues.size()) return true;
3356
Reid Spencerb83eb642006-10-20 07:07:24 +00003357 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003358 unsigned SrcByte;
3359 if (SI->getOpcode() == Instruction::Shl)
3360 SrcByte = DestByte - ShiftBytes;
3361 else
3362 SrcByte = DestByte + ShiftBytes;
3363
3364 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3365 if (SrcByte != ByteValues.size()-DestByte-1)
3366 return true;
3367
3368 // If the destination byte value is already defined, the values are or'd
3369 // together, which isn't a bswap (unless it's an or of the same bits).
3370 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3371 return true;
3372 ByteValues[DestByte] = SI->getOperand(0);
3373 return false;
3374}
3375
3376/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3377/// If so, insert the new bswap intrinsic and return it.
3378Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3379 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3380 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3381 return 0;
3382
3383 /// ByteValues - For each byte of the result, we keep track of which value
3384 /// defines each byte.
3385 std::vector<Value*> ByteValues;
3386 ByteValues.resize(I.getType()->getPrimitiveSize());
3387
3388 // Try to find all the pieces corresponding to the bswap.
3389 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3390 CollectBSwapParts(I.getOperand(1), ByteValues))
3391 return 0;
3392
3393 // Check to see if all of the bytes come from the same value.
3394 Value *V = ByteValues[0];
3395 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3396
3397 // Check to make sure that all of the bytes come from the same value.
3398 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3399 if (ByteValues[i] != V)
3400 return 0;
3401
3402 // If they do then *success* we can turn this into a bswap. Figure out what
3403 // bswap to make it into.
3404 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00003405 const char *FnName = 0;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003406 if (I.getType() == Type::UShortTy)
3407 FnName = "llvm.bswap.i16";
3408 else if (I.getType() == Type::UIntTy)
3409 FnName = "llvm.bswap.i32";
3410 else if (I.getType() == Type::ULongTy)
3411 FnName = "llvm.bswap.i64";
3412 else
3413 assert(0 && "Unknown integer type!");
3414 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3415
3416 return new CallInst(F, V);
3417}
3418
3419
Chris Lattner7e708292002-06-25 16:13:24 +00003420Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003421 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003422 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003423
Chris Lattnere87597f2004-10-16 18:11:37 +00003424 if (isa<UndefValue>(Op1))
3425 return ReplaceInstUsesWith(I, // X | undef -> -1
3426 ConstantIntegral::getAllOnesValue(I.getType()));
3427
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003428 // or X, X = X
3429 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003430 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003431
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003432 // See if we can simplify any instructions used by the instruction whose sole
3433 // purpose is to compute bits we don't care about.
3434 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003435 if (!isa<PackedType>(I.getType()) &&
3436 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003437 KnownZero, KnownOne))
3438 return &I;
3439
Chris Lattner3f5b8772002-05-06 16:14:14 +00003440 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003441 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003442 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003443 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3444 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003445 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3446 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003447 InsertNewInstBefore(Or, I);
3448 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3449 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003450
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003451 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3452 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3453 std::string Op0Name = Op0->getName(); Op0->setName("");
3454 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3455 InsertNewInstBefore(Or, I);
3456 return BinaryOperator::createXor(Or,
3457 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003458 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003459
3460 // Try to fold constant and into select arguments.
3461 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003463 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003464 if (isa<PHINode>(Op0))
3465 if (Instruction *NV = FoldOpIntoPhi(I))
3466 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003467 }
3468
Chris Lattner4f637d42006-01-06 17:59:59 +00003469 Value *A = 0, *B = 0;
3470 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003471
3472 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3473 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3474 return ReplaceInstUsesWith(I, Op1);
3475 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3476 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3477 return ReplaceInstUsesWith(I, Op0);
3478
Chris Lattner6423d4c2006-07-10 20:25:24 +00003479 // (A | B) | C and A | (B | C) -> bswap if possible.
3480 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003481 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003482 match(Op1, m_Or(m_Value(), m_Value())) ||
3483 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3484 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003485 if (Instruction *BSwap = MatchBSwap(I))
3486 return BSwap;
3487 }
3488
Chris Lattner6e4c6492005-05-09 04:58:36 +00003489 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3490 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003491 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003492 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3493 Op0->setName("");
3494 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3495 }
3496
3497 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3498 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003499 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003500 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3501 Op0->setName("");
3502 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3503 }
3504
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003505 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003506 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003507 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3508
3509 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3510 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3511
3512
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003513 // If we have: ((V + N) & C1) | (V & C2)
3514 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3515 // replace with V+N.
3516 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003517 Value *V1 = 0, *V2 = 0;
Reid Spencerb83eb642006-10-20 07:07:24 +00003518 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003519 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3520 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003521 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003522 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003523 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003524 return ReplaceInstUsesWith(I, A);
3525 }
3526 // Or commutes, try both ways.
Reid Spencerb83eb642006-10-20 07:07:24 +00003527 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003528 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3529 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003530 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003531 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003532 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003533 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003534 }
3535 }
3536 }
Chris Lattnere511b742006-11-14 07:46:50 +00003537
3538 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3539 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3540 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3541 if (SI0->getOpcode() == SI1->getOpcode() &&
3542 SI0->getOperand(1) == SI1->getOperand(1) &&
3543 (SI0->hasOneUse() || SI1->hasOneUse())) {
3544 Instruction *NewOp =
3545 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3546 SI1->getOperand(0),
3547 SI0->getName()), I);
3548 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3549 }
3550 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003551
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003552 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3553 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003554 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003555 ConstantIntegral::getAllOnesValue(I.getType()));
3556 } else {
3557 A = 0;
3558 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003559 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003560 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3561 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003562 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003563 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003564
Misha Brukmancb6267b2004-07-30 12:50:08 +00003565 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003566 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3567 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3568 I.getName()+".demorgan"), I);
3569 return BinaryOperator::createNot(And);
3570 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003571 }
Chris Lattnera2881962003-02-18 19:28:33 +00003572
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003573 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003574 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003575 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3576 return R;
3577
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003578 Value *LHSVal, *RHSVal;
3579 ConstantInt *LHSCst, *RHSCst;
3580 Instruction::BinaryOps LHSCC, RHSCC;
3581 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3582 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3583 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3584 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00003585 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003586 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3587 // Ensure that the larger constant is on the RHS.
3588 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3589 SetCondInst *LHS = cast<SetCondInst>(Op0);
3590 if (cast<ConstantBool>(Cmp)->getValue()) {
3591 std::swap(LHS, RHS);
3592 std::swap(LHSCst, RHSCst);
3593 std::swap(LHSCC, RHSCC);
3594 }
3595
3596 // At this point, we know we have have two setcc instructions
3597 // comparing a value against two constants and or'ing the result
3598 // together. Because of the above check, we know that we only have
3599 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3600 // FoldSetCCLogical check above), that the two constants are not
3601 // equal.
3602 assert(LHSCst != RHSCst && "Compares not folded above?");
3603
3604 switch (LHSCC) {
3605 default: assert(0 && "Unknown integer condition code!");
3606 case Instruction::SetEQ:
3607 switch (RHSCC) {
3608 default: assert(0 && "Unknown integer condition code!");
3609 case Instruction::SetEQ:
3610 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3611 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3612 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3613 LHSVal->getName()+".off");
3614 InsertNewInstBefore(Add, I);
3615 const Type *UnsType = Add->getType()->getUnsignedVersion();
3616 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3617 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3618 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3619 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3620 }
3621 break; // (X == 13 | X == 15) -> no change
3622
Chris Lattner240d6f42005-04-19 06:04:18 +00003623 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3624 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003625 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3626 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3627 return ReplaceInstUsesWith(I, RHS);
3628 }
3629 break;
3630 case Instruction::SetNE:
3631 switch (RHSCC) {
3632 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003633 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3634 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3635 return ReplaceInstUsesWith(I, LHS);
3636 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00003637 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner47811b72006-09-28 23:35:22 +00003638 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003639 }
3640 break;
3641 case Instruction::SetLT:
3642 switch (RHSCC) {
3643 default: assert(0 && "Unknown integer condition code!");
3644 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3645 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00003646 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3647 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003648 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3649 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3650 return ReplaceInstUsesWith(I, RHS);
3651 }
3652 break;
3653 case Instruction::SetGT:
3654 switch (RHSCC) {
3655 default: assert(0 && "Unknown integer condition code!");
3656 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3657 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3658 return ReplaceInstUsesWith(I, LHS);
3659 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3660 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner47811b72006-09-28 23:35:22 +00003661 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003662 }
3663 }
3664 }
3665 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003666
3667 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3668 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003669 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003670 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003671 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003672 // Only do this if the casts both really cause code to be generated.
3673 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3674 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003675 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3676 Op1C->getOperand(0),
3677 I.getName());
3678 InsertNewInstBefore(NewOp, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003679 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner6fc205f2006-05-05 06:39:07 +00003680 }
3681 }
3682
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003683
Chris Lattner7e708292002-06-25 16:13:24 +00003684 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003685}
3686
Chris Lattnerc317d392004-02-16 01:20:27 +00003687// XorSelf - Implements: X ^ X --> 0
3688struct XorSelf {
3689 Value *RHS;
3690 XorSelf(Value *rhs) : RHS(rhs) {}
3691 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3692 Instruction *apply(BinaryOperator &Xor) const {
3693 return &Xor;
3694 }
3695};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003696
3697
Chris Lattner7e708292002-06-25 16:13:24 +00003698Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003699 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003700 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003701
Chris Lattnere87597f2004-10-16 18:11:37 +00003702 if (isa<UndefValue>(Op1))
3703 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3704
Chris Lattnerc317d392004-02-16 01:20:27 +00003705 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3706 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3707 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003708 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003709 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003710
3711 // See if we can simplify any instructions used by the instruction whose sole
3712 // purpose is to compute bits we don't care about.
3713 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003714 if (!isa<PackedType>(I.getType()) &&
3715 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003716 KnownZero, KnownOne))
3717 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003718
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003719 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003720 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00003721 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003722 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner47811b72006-09-28 23:35:22 +00003723 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00003724 return new SetCondInst(SCI->getInverseCondition(),
3725 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003726
Chris Lattnerd65460f2003-11-05 01:06:05 +00003727 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003728 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3729 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003730 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3731 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003732 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003733 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003734 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003735
3736 // ~(~X & Y) --> (X | ~Y)
3737 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3738 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3739 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3740 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003741 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003742 Op0I->getOperand(1)->getName()+".not");
3743 InsertNewInstBefore(NotY, I);
3744 return BinaryOperator::createOr(Op0NotVal, NotY);
3745 }
3746 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003747
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003748 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003749 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003750 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003751 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003752 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3753 return BinaryOperator::createSub(
3754 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003755 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003756 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003757 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003758 } else if (Op0I->getOpcode() == Instruction::Or) {
3759 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3760 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3761 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3762 // Anything in both C1 and C2 is known to be zero, remove it from
3763 // NewRHS.
3764 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3765 NewRHS = ConstantExpr::getAnd(NewRHS,
3766 ConstantExpr::getNot(CommonBits));
3767 WorkList.push_back(Op0I);
3768 I.setOperand(0, Op0I->getOperand(0));
3769 I.setOperand(1, NewRHS);
3770 return &I;
3771 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003772 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003773 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003774
3775 // Try to fold constant and into select arguments.
3776 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003777 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003778 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003779 if (isa<PHINode>(Op0))
3780 if (Instruction *NV = FoldOpIntoPhi(I))
3781 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003782 }
3783
Chris Lattner8d969642003-03-10 23:06:50 +00003784 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003785 if (X == Op1)
3786 return ReplaceInstUsesWith(I,
3787 ConstantIntegral::getAllOnesValue(I.getType()));
3788
Chris Lattner8d969642003-03-10 23:06:50 +00003789 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003790 if (X == Op0)
3791 return ReplaceInstUsesWith(I,
3792 ConstantIntegral::getAllOnesValue(I.getType()));
3793
Chris Lattner64daab52006-04-01 08:03:55 +00003794 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00003795 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003796 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003797 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003798 I.swapOperands();
3799 std::swap(Op0, Op1);
3800 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003801 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003802 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003803 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003804 } else if (Op1I->getOpcode() == Instruction::Xor) {
3805 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3806 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3807 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3808 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003809 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3810 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3811 Op1I->swapOperands();
3812 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3813 I.swapOperands(); // Simplified below.
3814 std::swap(Op0, Op1);
3815 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003816 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003817
Chris Lattner64daab52006-04-01 08:03:55 +00003818 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00003819 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003820 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003821 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00003822 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00003823 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3824 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003825 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003826 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003827 } else if (Op0I->getOpcode() == Instruction::Xor) {
3828 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3829 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3830 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3831 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003832 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3833 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3834 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003835 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3836 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003837 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3838 InsertNewInstBefore(N, I);
3839 return BinaryOperator::createAnd(N, Op1);
3840 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003841 }
3842
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003843 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3844 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3845 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3846 return R;
3847
Chris Lattner6fc205f2006-05-05 06:39:07 +00003848 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3849 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003850 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003851 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003852 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003853 // Only do this if the casts both really cause code to be generated.
3854 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3855 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003856 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3857 Op1C->getOperand(0),
3858 I.getName());
3859 InsertNewInstBefore(NewOp, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003860 return CastInst::createInferredCast(NewOp, I.getType());
Chris Lattner6fc205f2006-05-05 06:39:07 +00003861 }
3862 }
Chris Lattnere511b742006-11-14 07:46:50 +00003863
3864 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
3865 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3866 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3867 if (SI0->getOpcode() == SI1->getOpcode() &&
3868 SI0->getOperand(1) == SI1->getOperand(1) &&
3869 (SI0->hasOneUse() || SI1->hasOneUse())) {
3870 Instruction *NewOp =
3871 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3872 SI1->getOperand(0),
3873 SI0->getName()), I);
3874 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3875 }
3876 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003877
Chris Lattner7e708292002-06-25 16:13:24 +00003878 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003879}
3880
Chris Lattnera96879a2004-09-29 17:40:11 +00003881static bool isPositive(ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003882 return C->getSExtValue() >= 0;
Chris Lattnera96879a2004-09-29 17:40:11 +00003883}
3884
3885/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3886/// overflowed for this type.
3887static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3888 ConstantInt *In2) {
3889 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3890
3891 if (In1->getType()->isUnsigned())
Reid Spencerb83eb642006-10-20 07:07:24 +00003892 return cast<ConstantInt>(Result)->getZExtValue() <
3893 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00003894 if (isPositive(In1) != isPositive(In2))
3895 return false;
3896 if (isPositive(In1))
Reid Spencerb83eb642006-10-20 07:07:24 +00003897 return cast<ConstantInt>(Result)->getSExtValue() <
3898 cast<ConstantInt>(In1)->getSExtValue();
3899 return cast<ConstantInt>(Result)->getSExtValue() >
3900 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00003901}
3902
Chris Lattner574da9b2005-01-13 20:14:25 +00003903/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3904/// code necessary to compute the offset from the base pointer (without adding
3905/// in the base pointer). Return the result as a signed integer of intptr size.
3906static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3907 TargetData &TD = IC.getTargetData();
3908 gep_type_iterator GTI = gep_type_begin(GEP);
3909 const Type *UIntPtrTy = TD.getIntPtrType();
3910 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3911 Value *Result = Constant::getNullValue(SIntPtrTy);
3912
3913 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003914 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003915
Chris Lattner574da9b2005-01-13 20:14:25 +00003916 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3917 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003918 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencerb83eb642006-10-20 07:07:24 +00003919 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner574da9b2005-01-13 20:14:25 +00003920 SIntPtrTy);
3921 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3922 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003923 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003924 Scale = ConstantExpr::getMul(OpC, Scale);
3925 if (Constant *RC = dyn_cast<Constant>(Result))
3926 Result = ConstantExpr::getAdd(RC, Scale);
3927 else {
3928 // Emit an add instruction.
3929 Result = IC.InsertNewInstBefore(
3930 BinaryOperator::createAdd(Result, Scale,
3931 GEP->getName()+".offs"), I);
3932 }
3933 }
3934 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003935 // Convert to correct type.
Reid Spencer3da59db2006-11-27 01:05:10 +00003936 Op = IC.InsertNewInstBefore(CastInst::createInferredCast(Op, SIntPtrTy,
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003937 Op->getName()+".c"), I);
3938 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003939 // We'll let instcombine(mul) convert this to a shl if possible.
3940 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3941 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003942
3943 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003944 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003945 GEP->getName()+".offs"), I);
3946 }
3947 }
3948 return Result;
3949}
3950
3951/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3952/// else. At this point we know that the GEP is on the LHS of the comparison.
3953Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3954 Instruction::BinaryOps Cond,
3955 Instruction &I) {
3956 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003957
3958 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3959 if (isa<PointerType>(CI->getOperand(0)->getType()))
3960 RHS = CI->getOperand(0);
3961
Chris Lattner574da9b2005-01-13 20:14:25 +00003962 Value *PtrBase = GEPLHS->getOperand(0);
3963 if (PtrBase == RHS) {
3964 // As an optimization, we don't actually have to compute the actual value of
3965 // OFFSET if this is a seteq or setne comparison, just return whether each
3966 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003967 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3968 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003969 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3970 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003971 bool EmitIt = true;
3972 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3973 if (isa<UndefValue>(C)) // undef index -> undef.
3974 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3975 if (C->isNullValue())
3976 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003977 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3978 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003979 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003980 return ReplaceInstUsesWith(I, // No comparison is needed here.
3981 ConstantBool::get(Cond == Instruction::SetNE));
3982 }
3983
3984 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003985 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003986 new SetCondInst(Cond, GEPLHS->getOperand(i),
3987 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3988 if (InVal == 0)
3989 InVal = Comp;
3990 else {
3991 InVal = InsertNewInstBefore(InVal, I);
3992 InsertNewInstBefore(Comp, I);
3993 if (Cond == Instruction::SetNE) // True if any are unequal
3994 InVal = BinaryOperator::createOr(InVal, Comp);
3995 else // True if all are equal
3996 InVal = BinaryOperator::createAnd(InVal, Comp);
3997 }
3998 }
3999 }
4000
4001 if (InVal)
4002 return InVal;
4003 else
4004 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4005 ConstantBool::get(Cond == Instruction::SetEQ));
4006 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004007
4008 // Only lower this if the setcc is the only user of the GEP or if we expect
4009 // the result to fold to a constant!
4010 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4011 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4012 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4013 return new SetCondInst(Cond, Offset,
4014 Constant::getNullValue(Offset->getType()));
4015 }
4016 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004017 // If the base pointers are different, but the indices are the same, just
4018 // compare the base pointer.
4019 if (PtrBase != GEPRHS->getOperand(0)) {
4020 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004021 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004022 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004023 if (IndicesTheSame)
4024 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4025 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4026 IndicesTheSame = false;
4027 break;
4028 }
4029
4030 // If all indices are the same, just compare the base pointers.
4031 if (IndicesTheSame)
4032 return new SetCondInst(Cond, GEPLHS->getOperand(0),
4033 GEPRHS->getOperand(0));
4034
4035 // Otherwise, the base pointers are different and the indices are
4036 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004037 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004038 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004039
Chris Lattnere9d782b2005-01-13 22:25:21 +00004040 // If one of the GEPs has all zero indices, recurse.
4041 bool AllZeros = true;
4042 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4043 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4044 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4045 AllZeros = false;
4046 break;
4047 }
4048 if (AllZeros)
4049 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4050 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004051
4052 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004053 AllZeros = true;
4054 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4055 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4056 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4057 AllZeros = false;
4058 break;
4059 }
4060 if (AllZeros)
4061 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4062
Chris Lattner4401c9c2005-01-14 00:20:05 +00004063 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4064 // If the GEPs only differ by one index, compare it.
4065 unsigned NumDifferences = 0; // Keep track of # differences.
4066 unsigned DiffOperand = 0; // The operand that differs.
4067 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4068 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004069 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4070 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004071 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004072 NumDifferences = 2;
4073 break;
4074 } else {
4075 if (NumDifferences++) break;
4076 DiffOperand = i;
4077 }
4078 }
4079
4080 if (NumDifferences == 0) // SAME GEP?
4081 return ReplaceInstUsesWith(I, // No comparison is needed here.
4082 ConstantBool::get(Cond == Instruction::SetEQ));
4083 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004084 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4085 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00004086
4087 // Convert the operands to signed values to make sure to perform a
4088 // signed comparison.
4089 const Type *NewTy = LHSV->getType()->getSignedVersion();
4090 if (LHSV->getType() != NewTy)
Reid Spencer811b0cb2006-10-26 19:19:06 +00004091 LHSV = InsertCastBefore(LHSV, NewTy, I);
Chris Lattner7911f032005-07-18 23:07:33 +00004092 if (RHSV->getType() != NewTy)
Reid Spencer811b0cb2006-10-26 19:19:06 +00004093 RHSV = InsertCastBefore(RHSV, NewTy, I);
Chris Lattner7911f032005-07-18 23:07:33 +00004094 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004095 }
4096 }
4097
Chris Lattner574da9b2005-01-13 20:14:25 +00004098 // Only lower this if the setcc is the only user of the GEP or if we expect
4099 // the result to fold to a constant!
4100 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4101 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4102 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4103 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4104 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4105 return new SetCondInst(Cond, L, R);
4106 }
4107 }
4108 return 0;
4109}
4110
4111
Chris Lattner484d3cf2005-04-24 06:59:08 +00004112Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004113 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4115 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00004116
4117 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00004118 if (Op0 == Op1)
4119 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00004120
Chris Lattnere87597f2004-10-16 18:11:37 +00004121 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
4122 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4123
Chris Lattner711b3402004-11-14 07:33:16 +00004124 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4125 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004126 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4127 isa<ConstantPointerNull>(Op0)) &&
4128 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004129 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00004130 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4131
4132 // setcc's with boolean values can always be turned into bitwise operations
4133 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00004134 switch (I.getOpcode()) {
4135 default: assert(0 && "Invalid setcc instruction!");
4136 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004137 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004138 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004139 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004140 }
Chris Lattner5dbef222004-08-11 00:50:51 +00004141 case Instruction::SetNE:
4142 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004143
Chris Lattner5dbef222004-08-11 00:50:51 +00004144 case Instruction::SetGT:
4145 std::swap(Op0, Op1); // Change setgt -> setlt
4146 // FALL THROUGH
4147 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
4148 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4149 InsertNewInstBefore(Not, I);
4150 return BinaryOperator::createAnd(Not, Op1);
4151 }
4152 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00004153 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00004154 // FALL THROUGH
4155 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4156 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4157 InsertNewInstBefore(Not, I);
4158 return BinaryOperator::createOr(Not, Op1);
4159 }
4160 }
Chris Lattner8b170942002-08-09 23:47:40 +00004161 }
4162
Chris Lattner2be51ae2004-06-09 04:24:29 +00004163 // See if we are doing a comparison between a constant and an instruction that
4164 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00004166 // Check to see if we are comparing against the minimum or maximum value...
4167 if (CI->isMinValue()) {
4168 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner47811b72006-09-28 23:35:22 +00004169 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004170 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner47811b72006-09-28 23:35:22 +00004171 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004172 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4173 return BinaryOperator::createSetEQ(Op0, Op1);
4174 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4175 return BinaryOperator::createSetNE(Op0, Op1);
4176
4177 } else if (CI->isMaxValue()) {
4178 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner47811b72006-09-28 23:35:22 +00004179 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004180 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner47811b72006-09-28 23:35:22 +00004181 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004182 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4183 return BinaryOperator::createSetEQ(Op0, Op1);
4184 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4185 return BinaryOperator::createSetNE(Op0, Op1);
4186
4187 // Comparing against a value really close to min or max?
4188 } else if (isMinValuePlusOne(CI)) {
4189 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4190 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4191 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4192 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4193
4194 } else if (isMaxValueMinusOne(CI)) {
4195 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4196 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4197 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4198 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4199 }
4200
4201 // If we still have a setle or setge instruction, turn it into the
4202 // appropriate setlt or setgt instruction. Since the border cases have
4203 // already been handled above, this requires little checking.
4204 //
4205 if (I.getOpcode() == Instruction::SetLE)
4206 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4207 if (I.getOpcode() == Instruction::SetGE)
4208 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4209
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004210
4211 // See if we can fold the comparison based on bits known to be zero or one
4212 // in the input.
4213 uint64_t KnownZero, KnownOne;
4214 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4215 KnownZero, KnownOne, 0))
4216 return &I;
4217
4218 // Given the known and unknown bits, compute a range that the LHS could be
4219 // in.
4220 if (KnownOne | KnownZero) {
4221 if (Ty->isUnsigned()) { // Unsigned comparison.
4222 uint64_t Min, Max;
4223 uint64_t RHSVal = CI->getZExtValue();
4224 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4225 Min, Max);
4226 switch (I.getOpcode()) { // LE/GE have been folded already.
4227 default: assert(0 && "Unknown setcc opcode!");
4228 case Instruction::SetEQ:
4229 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004230 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004231 break;
4232 case Instruction::SetNE:
4233 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004234 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004235 break;
4236 case Instruction::SetLT:
Chris Lattner47811b72006-09-28 23:35:22 +00004237 if (Max < RHSVal)
4238 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4239 if (Min > RHSVal)
4240 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004241 break;
4242 case Instruction::SetGT:
Chris Lattner47811b72006-09-28 23:35:22 +00004243 if (Min > RHSVal)
4244 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4245 if (Max < RHSVal)
4246 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004247 break;
4248 }
4249 } else { // Signed comparison.
4250 int64_t Min, Max;
4251 int64_t RHSVal = CI->getSExtValue();
4252 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4253 Min, Max);
4254 switch (I.getOpcode()) { // LE/GE have been folded already.
4255 default: assert(0 && "Unknown setcc opcode!");
4256 case Instruction::SetEQ:
4257 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004258 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004259 break;
4260 case Instruction::SetNE:
4261 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004262 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004263 break;
4264 case Instruction::SetLT:
Chris Lattner47811b72006-09-28 23:35:22 +00004265 if (Max < RHSVal)
4266 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4267 if (Min > RHSVal)
4268 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004269 break;
4270 case Instruction::SetGT:
Chris Lattner47811b72006-09-28 23:35:22 +00004271 if (Min > RHSVal)
4272 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4273 if (Max < RHSVal)
4274 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004275 break;
4276 }
4277 }
4278 }
4279
Reid Spencer1628cec2006-10-26 06:15:43 +00004280 // Since the RHS is a constantInt (CI), if the left hand side is an
4281 // instruction, see if that instruction also has constants so that the
4282 // instruction can be folded into the setcc
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004283 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00004284 switch (LHSI->getOpcode()) {
4285 case Instruction::And:
4286 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4287 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattnere695a3b2006-09-18 05:27:43 +00004288 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4289
4290 // If an operand is an AND of a truncating cast, we can widen the
4291 // and/compare to be the input width without changing the value
4292 // produced, eliminating a cast.
4293 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4294 // We can do this transformation if either the AND constant does not
4295 // have its sign bit set or if it is an equality comparison.
4296 // Extending a relational comparison when we're checking the sign
4297 // bit would not work.
Reid Spencer3da59db2006-11-27 01:05:10 +00004298 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
Chris Lattnere695a3b2006-09-18 05:27:43 +00004299 (I.isEquality() ||
4300 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4301 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4302 ConstantInt *NewCST;
4303 ConstantInt *NewCI;
4304 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004305 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004306 AndCST->getZExtValue());
Reid Spencerb83eb642006-10-20 07:07:24 +00004307 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004308 CI->getZExtValue());
4309 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004310 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004311 AndCST->getZExtValue());
Reid Spencerb83eb642006-10-20 07:07:24 +00004312 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004313 CI->getZExtValue());
4314 }
4315 Instruction *NewAnd =
4316 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4317 LHSI->getName());
4318 InsertNewInstBefore(NewAnd, I);
4319 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4320 }
4321 }
4322
Chris Lattner648e3bc2004-09-23 21:52:49 +00004323 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4324 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4325 // happens a LOT in code produced by the C front-end, for bitfield
4326 // access.
4327 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004328
4329 // Check to see if there is a noop-cast between the shift and the and.
4330 if (!Shift) {
4331 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4332 if (CI->getOperand(0)->getType()->isIntegral() &&
4333 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4334 CI->getType()->getPrimitiveSizeInBits())
4335 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4336 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004337
Reid Spencerb83eb642006-10-20 07:07:24 +00004338 ConstantInt *ShAmt;
4339 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004340 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4341 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00004342
Chris Lattner648e3bc2004-09-23 21:52:49 +00004343 // We can fold this as long as we can't shift unknown bits
4344 // into the mask. This can only happen with signed shift
4345 // rights, as they sign-extend.
4346 if (ShAmt) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004347 bool CanFold = Shift->isLogicalShift();
Chris Lattner648e3bc2004-09-23 21:52:49 +00004348 if (!CanFold) {
4349 // To test for the bad case of the signed shr, see if any
4350 // of the bits shifted in could be tested after the mask.
Reid Spencerb83eb642006-10-20 07:07:24 +00004351 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00004352 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4353
Reid Spencerb83eb642006-10-20 07:07:24 +00004354 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00004355 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004356 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4357 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00004358 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4359 CanFold = true;
4360 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004361
Chris Lattner648e3bc2004-09-23 21:52:49 +00004362 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00004363 Constant *NewCst;
4364 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004365 NewCst = ConstantExpr::getLShr(CI, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004366 else
4367 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004368
Chris Lattner648e3bc2004-09-23 21:52:49 +00004369 // Check to see if we are shifting out any of the bits being
4370 // compared.
4371 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4372 // If we shifted bits out, the fold is not going to work out.
4373 // As a special case, check to see if this means that the
4374 // result is always true or false now.
4375 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner47811b72006-09-28 23:35:22 +00004376 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004377 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner47811b72006-09-28 23:35:22 +00004378 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004379 } else {
4380 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004381 Constant *NewAndCST;
4382 if (Shift->getOpcode() == Instruction::Shl)
Reid Spencer3822ff52006-11-08 06:47:33 +00004383 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004384 else
4385 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4386 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004387 if (AndTy == Ty)
4388 LHSI->setOperand(0, Shift->getOperand(0));
4389 else {
4390 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4391 *Shift);
4392 LHSI->setOperand(0, NewCast);
4393 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004394 WorkList.push_back(Shift); // Shift is dead.
4395 AddUsesToWorkList(I);
4396 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00004397 }
4398 }
Chris Lattner457dd822004-06-09 07:59:58 +00004399 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004400
4401 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4402 // preferable because it allows the C<<Y expression to be hoisted out
4403 // of a loop if Y is invariant and X is not.
4404 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattner6d7ca922006-09-18 18:27:05 +00004405 I.isEquality() && !Shift->isArithmeticShift() &&
4406 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004407 // Compute C << Y.
4408 Value *NS;
Reid Spencer3822ff52006-11-08 06:47:33 +00004409 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004410 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4411 "tmp");
4412 } else {
4413 // Make sure we insert a logical shift.
Chris Lattnere695a3b2006-09-18 05:27:43 +00004414 Constant *NewAndCST = AndCST;
Chris Lattner65b72ba2006-09-18 04:22:48 +00004415 if (AndCST->getType()->isSigned())
Chris Lattnere695a3b2006-09-18 05:27:43 +00004416 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattner65b72ba2006-09-18 04:22:48 +00004417 AndCST->getType()->getUnsignedVersion());
Reid Spencer3822ff52006-11-08 06:47:33 +00004418 NS = new ShiftInst(Instruction::LShr, NewAndCST,
Chris Lattnere695a3b2006-09-18 05:27:43 +00004419 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004420 }
4421 InsertNewInstBefore(cast<Instruction>(NS), I);
4422
4423 // If C's sign doesn't agree with the and, insert a cast now.
4424 if (NS->getType() != LHSI->getType())
4425 NS = InsertCastBefore(NS, LHSI->getType(), I);
4426
4427 Value *ShiftOp = Shift->getOperand(0);
4428 if (ShiftOp->getType() != LHSI->getType())
4429 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4430
4431 // Compute X & (C << Y).
4432 Instruction *NewAnd =
4433 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4434 InsertNewInstBefore(NewAnd, I);
4435
4436 I.setOperand(0, NewAnd);
4437 return &I;
4438 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004439 }
4440 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00004441
Chris Lattner18d19ca2004-09-28 18:22:15 +00004442 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004443 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004444 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004445 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4446
4447 // Check that the shift amount is in range. If not, don't perform
4448 // undefined shifts. When the shift is visited it will be
4449 // simplified.
Reid Spencerb83eb642006-10-20 07:07:24 +00004450 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004451 break;
4452
Chris Lattner18d19ca2004-09-28 18:22:15 +00004453 // If we are comparing against bits always shifted out, the
4454 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00004455 Constant *Comp =
Reid Spencer3822ff52006-11-08 06:47:33 +00004456 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004457 if (Comp != CI) {// Comparing against a bit that we know is zero.
4458 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4459 Constant *Cst = ConstantBool::get(IsSetNE);
4460 return ReplaceInstUsesWith(I, Cst);
4461 }
4462
4463 if (LHSI->hasOneUse()) {
4464 // Otherwise strength reduce the shift into an and.
Reid Spencerb83eb642006-10-20 07:07:24 +00004465 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004466 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4467
4468 Constant *Mask;
4469 if (CI->getType()->isUnsigned()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004470 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004471 } else if (ShAmtVal != 0) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004472 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004473 } else {
4474 Mask = ConstantInt::getAllOnesValue(CI->getType());
4475 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004476
Chris Lattner18d19ca2004-09-28 18:22:15 +00004477 Instruction *AndI =
4478 BinaryOperator::createAnd(LHSI->getOperand(0),
4479 Mask, LHSI->getName()+".mask");
4480 Value *And = InsertNewInstBefore(AndI, I);
4481 return new SetCondInst(I.getOpcode(), And,
Reid Spencer3822ff52006-11-08 06:47:33 +00004482 ConstantExpr::getLShr(CI, ShAmt));
Chris Lattner18d19ca2004-09-28 18:22:15 +00004483 }
4484 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00004485 }
4486 break;
4487
Reid Spencer3822ff52006-11-08 06:47:33 +00004488 case Instruction::LShr: // (setcc (shr X, ShAmt), CI)
4489 case Instruction::AShr:
Reid Spencerb83eb642006-10-20 07:07:24 +00004490 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004491 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004492 // Check that the shift amount is in range. If not, don't perform
4493 // undefined shifts. When the shift is visited it will be
4494 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00004495 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00004496 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004497 break;
4498
Chris Lattnerf63f6472004-09-27 16:18:50 +00004499 // If we are comparing against bits always shifted out, the
4500 // comparison cannot succeed.
Reid Spencer3822ff52006-11-08 06:47:33 +00004501 Constant *Comp;
4502 if (CI->getType()->isUnsigned())
4503 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4504 ShAmt);
4505 else
4506 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4507 ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00004508
Chris Lattnerf63f6472004-09-27 16:18:50 +00004509 if (Comp != CI) {// Comparing against a bit that we know is zero.
4510 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4511 Constant *Cst = ConstantBool::get(IsSetNE);
4512 return ReplaceInstUsesWith(I, Cst);
4513 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004514
Chris Lattnerf63f6472004-09-27 16:18:50 +00004515 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004516 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004517
Chris Lattnerf63f6472004-09-27 16:18:50 +00004518 // Otherwise strength reduce the shift into an and.
4519 uint64_t Val = ~0ULL; // All ones.
4520 Val <<= ShAmtVal; // Shift over to the right spot.
4521
4522 Constant *Mask;
4523 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00004524 Val &= ~0ULL >> (64-TypeBits);
Reid Spencerb83eb642006-10-20 07:07:24 +00004525 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004526 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004527 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004528 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004529
Chris Lattnerf63f6472004-09-27 16:18:50 +00004530 Instruction *AndI =
4531 BinaryOperator::createAnd(LHSI->getOperand(0),
4532 Mask, LHSI->getName()+".mask");
4533 Value *And = InsertNewInstBefore(AndI, I);
4534 return new SetCondInst(I.getOpcode(), And,
4535 ConstantExpr::getShl(CI, ShAmt));
4536 }
Chris Lattnerf63f6472004-09-27 16:18:50 +00004537 }
4538 }
4539 break;
Chris Lattner0c967662004-09-24 15:21:34 +00004540
Reid Spencer1628cec2006-10-26 06:15:43 +00004541 case Instruction::SDiv:
4542 case Instruction::UDiv:
4543 // Fold: setcc ([us]div X, C1), C2 -> range test
4544 // Fold this div into the comparison, producing a range check.
4545 // Determine, based on the divide type, what the range is being
4546 // checked. If there is an overflow on the low or high side, remember
4547 // it, otherwise compute the range [low, hi) bounding the new value.
4548 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattnera96879a2004-09-29 17:40:11 +00004549 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00004550 // FIXME: If the operand types don't match the type of the divide
4551 // then don't attempt this transform. The code below doesn't have the
4552 // logic to deal with a signed divide and an unsigned compare (and
4553 // vice versa). This is because (x /s C1) <s C2 produces different
4554 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4555 // (x /u C1) <u C2. Simply casting the operands and result won't
4556 // work. :( The if statement below tests that condition and bails
4557 // if it finds it.
Reid Spencer3da59db2006-11-27 01:05:10 +00004558 const Type *DivRHSTy = DivRHS->getType();
Reid Spencer1628cec2006-10-26 06:15:43 +00004559 unsigned DivOpCode = LHSI->getOpcode();
4560 if (I.isEquality() &&
4561 ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4562 (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4563 break;
4564
4565 // Initialize the variables that will indicate the nature of the
4566 // range check.
4567 bool LoOverflow = false, HiOverflow = false;
Chris Lattnera96879a2004-09-29 17:40:11 +00004568 ConstantInt *LoBound = 0, *HiBound = 0;
4569
Reid Spencer1628cec2006-10-26 06:15:43 +00004570 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4571 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4572 // C2 (CI). By solving for X we can turn this into a range check
4573 // instead of computing a divide.
4574 ConstantInt *Prod =
4575 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
Chris Lattnera96879a2004-09-29 17:40:11 +00004576
Reid Spencer1628cec2006-10-26 06:15:43 +00004577 // Determine if the product overflows by seeing if the product is
4578 // not equal to the divide. Make sure we do the same kind of divide
4579 // as in the LHS instruction that we're folding.
4580 bool ProdOV = !DivRHS->isNullValue() &&
4581 (DivOpCode == Instruction::SDiv ?
4582 ConstantExpr::getSDiv(Prod, DivRHS) :
4583 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4584
4585 // Get the SetCC opcode
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004586 Instruction::BinaryOps Opcode = I.getOpcode();
4587
Reid Spencer1628cec2006-10-26 06:15:43 +00004588 if (DivRHS->isNullValue()) {
4589 // Don't hack on divide by zeros!
4590 } else if (DivOpCode == Instruction::UDiv) { // udiv
Chris Lattnera96879a2004-09-29 17:40:11 +00004591 LoBound = Prod;
4592 LoOverflow = ProdOV;
4593 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
Reid Spencer1628cec2006-10-26 06:15:43 +00004594 } else if (isPositive(DivRHS)) { // Divisor is > 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004595 if (CI->isNullValue()) { // (X / pos) op 0
4596 // Can't overflow.
4597 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4598 HiBound = DivRHS;
4599 } else if (isPositive(CI)) { // (X / pos) op pos
4600 LoBound = Prod;
4601 LoOverflow = ProdOV;
4602 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4603 } else { // (X / pos) op neg
4604 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4605 LoOverflow = AddWithOverflow(LoBound, Prod,
4606 cast<ConstantInt>(DivRHSH));
4607 HiBound = Prod;
4608 HiOverflow = ProdOV;
4609 }
Reid Spencer1628cec2006-10-26 06:15:43 +00004610 } else { // Divisor is < 0.
Chris Lattnera96879a2004-09-29 17:40:11 +00004611 if (CI->isNullValue()) { // (X / neg) op 0
4612 LoBound = AddOne(DivRHS);
4613 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00004614 if (HiBound == DivRHS)
Reid Spencer1628cec2006-10-26 06:15:43 +00004615 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00004616 } else if (isPositive(CI)) { // (X / neg) op pos
4617 HiOverflow = LoOverflow = ProdOV;
4618 if (!LoOverflow)
4619 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4620 HiBound = AddOne(Prod);
4621 } else { // (X / neg) op neg
4622 LoBound = Prod;
4623 LoOverflow = HiOverflow = ProdOV;
4624 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4625 }
Chris Lattner340a05f2004-10-08 19:15:44 +00004626
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004627 // Dividing by a negate swaps the condition.
4628 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00004629 }
4630
4631 if (LoBound) {
4632 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004633 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00004634 default: assert(0 && "Unhandled setcc opcode!");
4635 case Instruction::SetEQ:
4636 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004637 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004638 else if (HiOverflow)
4639 return new SetCondInst(Instruction::SetGE, X, LoBound);
4640 else if (LoOverflow)
4641 return new SetCondInst(Instruction::SetLT, X, HiBound);
4642 else
4643 return InsertRangeTest(X, LoBound, HiBound, true, I);
4644 case Instruction::SetNE:
4645 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004646 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004647 else if (HiOverflow)
4648 return new SetCondInst(Instruction::SetLT, X, LoBound);
4649 else if (LoOverflow)
4650 return new SetCondInst(Instruction::SetGE, X, HiBound);
4651 else
4652 return InsertRangeTest(X, LoBound, HiBound, false, I);
4653 case Instruction::SetLT:
4654 if (LoOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004655 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004656 return new SetCondInst(Instruction::SetLT, X, LoBound);
4657 case Instruction::SetGT:
4658 if (HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004659 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004660 return new SetCondInst(Instruction::SetGE, X, HiBound);
4661 }
4662 }
4663 }
4664 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00004665 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004666
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004667 // Simplify seteq and setne instructions...
Chris Lattner65b72ba2006-09-18 04:22:48 +00004668 if (I.isEquality()) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004669 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4670
Reid Spencerb83eb642006-10-20 07:07:24 +00004671 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4672 // the second operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00004673 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4674 switch (BO->getOpcode()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004675 case Instruction::SRem:
4676 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4677 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4678 BO->hasOneUse()) {
4679 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4680 if (V > 1 && isPowerOf2_64(V)) {
Reid Spencer0a783f72006-11-02 01:53:59 +00004681 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4682 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
Chris Lattner3571b722004-07-06 07:38:18 +00004683 return BinaryOperator::create(I.getOpcode(), NewRem,
Reid Spencer0a783f72006-11-02 01:53:59 +00004684 Constant::getNullValue(BO->getType()));
Chris Lattner3571b722004-07-06 07:38:18 +00004685 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004686 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004687 break;
Chris Lattner934754b2003-08-13 05:33:12 +00004688 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00004689 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4690 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00004691 if (BO->hasOneUse())
4692 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4693 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00004694 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004695 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4696 // efficiently invertible, or if the add has just this one use.
4697 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004698
Chris Lattner934754b2003-08-13 05:33:12 +00004699 if (Value *NegVal = dyn_castNegVal(BOp1))
4700 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4701 else if (Value *NegVal = dyn_castNegVal(BOp0))
4702 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00004703 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004704 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4705 BO->setName("");
4706 InsertNewInstBefore(Neg, I);
4707 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4708 }
4709 }
4710 break;
4711 case Instruction::Xor:
4712 // For the xor case, we can xor two constants together, eliminating
4713 // the explicit xor.
4714 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4715 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00004716 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00004717
4718 // FALLTHROUGH
4719 case Instruction::Sub:
4720 // Replace (([sub|xor] A, B) != 0) with (A != B)
4721 if (CI->isNullValue())
4722 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4723 BO->getOperand(1));
4724 break;
4725
4726 case Instruction::Or:
4727 // If bits are being or'd in that are not present in the constant we
4728 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00004729 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00004730 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00004731 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004732 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00004733 }
Chris Lattner934754b2003-08-13 05:33:12 +00004734 break;
4735
4736 case Instruction::And:
4737 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004738 // If bits are being compared against that are and'd out, then the
4739 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00004740 if (!ConstantExpr::getAnd(CI,
4741 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004742 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00004743
Chris Lattner457dd822004-06-09 07:59:58 +00004744 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00004745 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00004746 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4747 Instruction::SetNE, Op0,
4748 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00004749
Chris Lattner934754b2003-08-13 05:33:12 +00004750 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4751 // to be a signed value as appropriate.
4752 if (isSignBit(BOC)) {
4753 Value *X = BO->getOperand(0);
4754 // If 'X' is not signed, insert a cast now...
4755 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00004756 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00004757 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00004758 }
4759 return new SetCondInst(isSetNE ? Instruction::SetLT :
4760 Instruction::SetGE, X,
4761 Constant::getNullValue(X->getType()));
4762 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004763
Chris Lattner83c4ec02004-09-27 19:29:18 +00004764 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004765 if (CI->isNullValue() && isHighOnes(BOC)) {
4766 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004767 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004768
4769 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00004770 if (NegX->getType()->isSigned()) {
4771 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4772 X = InsertCastBefore(X, DestTy, I);
4773 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004774 }
4775
4776 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00004777 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004778 }
4779
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004780 }
Chris Lattner934754b2003-08-13 05:33:12 +00004781 default: break;
4782 }
4783 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004784 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00004785 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004786 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4787 Value *CastOp = Cast->getOperand(0);
4788 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004789 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004790 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004791 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004792 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004793 "Source and destination signednesses should differ!");
4794 if (Cast->getType()->isSigned()) {
4795 // If this is a signed comparison, check for comparisons in the
4796 // vicinity of zero.
4797 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4798 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00004799 return BinaryOperator::createSetGT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004800 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004801 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004802 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004803 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00004804 return BinaryOperator::createSetLT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004805 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004806 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004807 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004808 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004809 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004810 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00004811 return BinaryOperator::createSetGT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004812 ConstantInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004813 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004814 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004815 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00004816 return BinaryOperator::createSetLT(CastOp,
4817 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004818 }
4819 }
4820 }
Chris Lattner40f5d702003-06-04 05:10:11 +00004821 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004822 }
4823
Chris Lattner6970b662005-04-23 15:31:55 +00004824 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4825 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4826 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4827 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004828 case Instruction::GetElementPtr:
4829 if (RHSC->isNullValue()) {
4830 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4831 bool isAllZeros = true;
4832 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4833 if (!isa<Constant>(LHSI->getOperand(i)) ||
4834 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4835 isAllZeros = false;
4836 break;
4837 }
4838 if (isAllZeros)
4839 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4840 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4841 }
4842 break;
4843
Chris Lattner6970b662005-04-23 15:31:55 +00004844 case Instruction::PHI:
4845 if (Instruction *NV = FoldOpIntoPhi(I))
4846 return NV;
4847 break;
4848 case Instruction::Select:
4849 // If either operand of the select is a constant, we can fold the
4850 // comparison into the select arms, which will cause one to be
4851 // constant folded and the select turned into a bitwise or.
4852 Value *Op1 = 0, *Op2 = 0;
4853 if (LHSI->hasOneUse()) {
4854 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4855 // Fold the known value into the constant operand.
4856 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4857 // Insert a new SetCC of the other select operand.
4858 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4859 LHSI->getOperand(2), RHSC,
4860 I.getName()), I);
4861 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4862 // Fold the known value into the constant operand.
4863 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4864 // Insert a new SetCC of the other select operand.
4865 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4866 LHSI->getOperand(1), RHSC,
4867 I.getName()), I);
4868 }
4869 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004870
Chris Lattner6970b662005-04-23 15:31:55 +00004871 if (Op1)
4872 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4873 break;
4874 }
4875 }
4876
Chris Lattner574da9b2005-01-13 20:14:25 +00004877 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4878 if (User *GEP = dyn_castGetElementPtr(Op0))
4879 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4880 return NI;
4881 if (User *GEP = dyn_castGetElementPtr(Op1))
4882 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4883 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4884 return NI;
4885
Chris Lattnerde90b762003-11-03 04:25:02 +00004886 // Test to see if the operands of the setcc are casted versions of other
4887 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00004888 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4889 Value *CastOp0 = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00004890 if (CI->isLosslessCast() && I.isEquality() &&
4891 (isa<Constant>(Op1) || isa<CastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00004892 // We keep moving the cast from the left operand over to the right
4893 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00004894 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00004895
Chris Lattnerde90b762003-11-03 04:25:02 +00004896 // If operand #1 is a cast instruction, see if we can eliminate it as
4897 // well.
Reid Spencer3da59db2006-11-27 01:05:10 +00004898 if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) {
4899 Value *CI2Op0 = CI2->getOperand(0);
4900 if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4901 Op1 = CI2Op0;
4902 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004903
Chris Lattnerde90b762003-11-03 04:25:02 +00004904 // If Op1 is a constant, we can fold the cast into the constant.
4905 if (Op1->getType() != Op0->getType())
4906 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4907 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4908 } else {
4909 // Otherwise, cast the RHS right before the setcc
Reid Spencer811b0cb2006-10-26 19:19:06 +00004910 Op1 = InsertCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004911 }
4912 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4913 }
4914
Chris Lattner68708052003-11-03 05:17:03 +00004915 // Handle the special case of: setcc (cast bool to X), <cst>
4916 // This comes up when you have code like
4917 // int X = A < B;
4918 // if (X) ...
4919 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00004920 // with a constant or another cast from the same type.
4921 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4922 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4923 return R;
Chris Lattner68708052003-11-03 05:17:03 +00004924 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00004925
Chris Lattner65b72ba2006-09-18 04:22:48 +00004926 if (I.isEquality()) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00004927 Value *A, *B;
4928 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4929 (A == Op1 || B == Op1)) {
4930 // (A^B) == A -> B == 0
4931 Value *OtherVal = A == Op1 ? B : A;
4932 return BinaryOperator::create(I.getOpcode(), OtherVal,
4933 Constant::getNullValue(A->getType()));
4934 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4935 (A == Op0 || B == Op0)) {
4936 // A == (A^B) -> B == 0
4937 Value *OtherVal = A == Op0 ? B : A;
4938 return BinaryOperator::create(I.getOpcode(), OtherVal,
4939 Constant::getNullValue(A->getType()));
4940 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4941 // (A-B) == A -> B == 0
4942 return BinaryOperator::create(I.getOpcode(), B,
4943 Constant::getNullValue(B->getType()));
4944 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4945 // A == (A-B) -> B == 0
4946 return BinaryOperator::create(I.getOpcode(), B,
4947 Constant::getNullValue(B->getType()));
4948 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00004949
4950 Value *C, *D;
4951 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4952 if (Op0->hasOneUse() && Op1->hasOneUse() &&
4953 match(Op0, m_And(m_Value(A), m_Value(B))) &&
4954 match(Op1, m_And(m_Value(C), m_Value(D)))) {
4955 Value *X = 0, *Y = 0, *Z = 0;
4956
4957 if (A == C) {
4958 X = B; Y = D; Z = A;
4959 } else if (A == D) {
4960 X = B; Y = C; Z = A;
4961 } else if (B == C) {
4962 X = A; Y = D; Z = B;
4963 } else if (B == D) {
4964 X = A; Y = C; Z = B;
4965 }
4966
4967 if (X) { // Build (X^Y) & Z
4968 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
4969 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
4970 I.setOperand(0, Op1);
4971 I.setOperand(1, Constant::getNullValue(Op1->getType()));
4972 return &I;
4973 }
4974 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00004975 }
Chris Lattner7e708292002-06-25 16:13:24 +00004976 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004977}
4978
Chris Lattner484d3cf2005-04-24 06:59:08 +00004979// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4980// We only handle extending casts so far.
4981//
4982Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004983 const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
4984 Value *LHSCIOp = LHSCI->getOperand(0);
4985 const Type *SrcTy = LHSCIOp->getType();
4986 const Type *DestTy = SCI.getOperand(0)->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004987 Value *RHSCIOp;
4988
4989 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004990 return 0;
4991
Chris Lattner484d3cf2005-04-24 06:59:08 +00004992 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4993 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4994 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4995
4996 // Is this a sign or zero extension?
4997 bool isSignSrc = SrcTy->isSigned();
4998 bool isSignDest = DestTy->isSigned();
4999
5000 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5001 // Not an extension from the same type?
5002 RHSCIOp = CI->getOperand(0);
5003 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5004 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5005 // Compute the constant that would happen if we truncated to SrcTy then
5006 // reextended to DestTy.
Reid Spencer3da59db2006-11-27 01:05:10 +00005007 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5008 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
Chris Lattner484d3cf2005-04-24 06:59:08 +00005009
Reid Spencer3da59db2006-11-27 01:05:10 +00005010 if (Res2 == CI) {
Devang Patel6ce890b2006-10-19 18:54:08 +00005011 // Make sure that src sign and dest sign match. For example,
5012 //
5013 // %A = cast short %X to uint
5014 // %B = setgt uint %A, 1330
5015 //
Devang Pateldf308fa2006-10-19 19:21:36 +00005016 // It is incorrect to transform this into
Devang Patel6ce890b2006-10-19 18:54:08 +00005017 //
5018 // %B = setgt short %X, 1330
5019 //
5020 // because %A may have negative value.
Devang Patel002e4992006-10-19 20:59:13 +00005021 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5022 // OR operation is EQ/NE.
5023 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Reid Spencer3da59db2006-11-27 01:05:10 +00005024 RHSCIOp = Res1;
Devang Patel6ce890b2006-10-19 18:54:08 +00005025 else
5026 return 0;
Chris Lattner484d3cf2005-04-24 06:59:08 +00005027 } else {
5028 // If the value cannot be represented in the shorter type, we cannot emit
5029 // a simple comparison.
5030 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner47811b72006-09-28 23:35:22 +00005031 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattner484d3cf2005-04-24 06:59:08 +00005032 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner47811b72006-09-28 23:35:22 +00005033 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattner484d3cf2005-04-24 06:59:08 +00005034
Chris Lattner484d3cf2005-04-24 06:59:08 +00005035 // Evaluate the comparison for LT.
5036 Value *Result;
5037 if (DestTy->isSigned()) {
5038 // We're performing a signed comparison.
5039 if (isSignSrc) {
5040 // Signed extend and signed comparison.
Reid Spencerb83eb642006-10-20 07:07:24 +00005041 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner47811b72006-09-28 23:35:22 +00005042 Result = ConstantBool::getFalse();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005043 else
Reid Spencerb83eb642006-10-20 07:07:24 +00005044 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattner484d3cf2005-04-24 06:59:08 +00005045 } else {
5046 // Unsigned extend and signed comparison.
Reid Spencerb83eb642006-10-20 07:07:24 +00005047 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner47811b72006-09-28 23:35:22 +00005048 Result = ConstantBool::getFalse();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005049 else
Chris Lattner47811b72006-09-28 23:35:22 +00005050 Result = ConstantBool::getTrue();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005051 }
5052 } else {
5053 // We're performing an unsigned comparison.
5054 if (!isSignSrc) {
5055 // Unsigned extend & compare -> always true.
Chris Lattner47811b72006-09-28 23:35:22 +00005056 Result = ConstantBool::getTrue();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005057 } else {
5058 // We're performing an unsigned comp with a sign extended value.
5059 // This is true if the input is >= 0. [aka >s -1]
5060 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5061 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5062 NegOne, SCI.getName()), SCI);
5063 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00005064 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00005065
Jeff Cohen00b168892005-07-27 06:12:32 +00005066 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00005067 if (SCI.getOpcode() == Instruction::SetLT) {
5068 return ReplaceInstUsesWith(SCI, Result);
5069 } else {
5070 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5071 if (Constant *CI = dyn_cast<Constant>(Result))
5072 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5073 else
5074 return BinaryOperator::createNot(Result);
5075 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00005076 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00005077 } else {
5078 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00005079 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005080
Chris Lattner8d7089e2005-06-16 03:00:08 +00005081 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00005082 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5083}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005084
Chris Lattnerea340052003-03-10 19:16:08 +00005085Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00005086 assert(I.getOperand(1)->getType() == Type::UByteTy);
5087 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00005088 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005089
5090 // shl X, 0 == X and shr X, 0 == X
5091 // shl 0, X == 0 and shr 0, X == 0
5092 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00005093 Op0 == Constant::getNullValue(Op0->getType()))
5094 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005095
Chris Lattnere87597f2004-10-16 18:11:37 +00005096 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
5097 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00005098 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00005099 else // undef << X -> 0 AND undef >>u X -> 0
5100 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5101 }
5102 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00005103 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00005104 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5105 else
5106 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
5107 }
5108
Chris Lattnerde2b6602006-11-10 23:38:52 +00005109 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5110 if (I.getOpcode() == Instruction::AShr)
Reid Spencerb83eb642006-10-20 07:07:24 +00005111 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattnerde2b6602006-11-10 23:38:52 +00005112 if (CSI->isAllOnesValue())
Chris Lattnerdf17af12003-08-12 21:53:41 +00005113 return ReplaceInstUsesWith(I, CSI);
5114
Chris Lattner2eefe512004-04-09 19:05:30 +00005115 // Try to fold constant and into select arguments.
5116 if (isa<Constant>(Op0))
5117 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005118 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005119 return R;
5120
Chris Lattner120347e2005-05-08 17:34:56 +00005121 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00005122 if (I.isArithmeticShift()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00005123 if (MaskedValueIsZero(Op0,
5124 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Reid Spencer3822ff52006-11-08 06:47:33 +00005125 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
Chris Lattner120347e2005-05-08 17:34:56 +00005126 }
5127 }
Jeff Cohen00b168892005-07-27 06:12:32 +00005128
Reid Spencerb83eb642006-10-20 07:07:24 +00005129 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5130 if (CUI->getType()->isUnsigned())
5131 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5132 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005133 return 0;
5134}
5135
Reid Spencerb83eb642006-10-20 07:07:24 +00005136Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005137 ShiftInst &I) {
5138 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Reid Spencer3822ff52006-11-08 06:47:33 +00005139 bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() :
5140 I.getOpcode() == Instruction::AShr;
Chris Lattner830ed032006-01-06 07:22:22 +00005141 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005142
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00005143 // See if we can simplify any instructions used by the instruction whose sole
5144 // purpose is to compute bits we don't care about.
5145 uint64_t KnownZero, KnownOne;
5146 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5147 KnownZero, KnownOne))
5148 return &I;
5149
Chris Lattner4d5542c2006-01-06 07:12:35 +00005150 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5151 // of a signed value.
5152 //
5153 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00005154 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00005155 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00005156 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5157 else {
Reid Spencerb83eb642006-10-20 07:07:24 +00005158 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00005159 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00005160 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005161 }
5162
5163 // ((X*C1) << C2) == (X * (C1 << C2))
5164 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5165 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5166 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5167 return BinaryOperator::createMul(BO->getOperand(0),
5168 ConstantExpr::getShl(BOOp, Op1));
5169
5170 // Try to fold constant and into select arguments.
5171 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5172 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5173 return R;
5174 if (isa<PHINode>(Op0))
5175 if (Instruction *NV = FoldOpIntoPhi(I))
5176 return NV;
5177
5178 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00005179 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5180 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5181 Value *V1, *V2;
5182 ConstantInt *CC;
5183 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00005184 default: break;
5185 case Instruction::Add:
5186 case Instruction::And:
5187 case Instruction::Or:
5188 case Instruction::Xor:
5189 // These operators commute.
5190 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005191 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5192 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005193 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005194 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005195 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005196 Op0BO->getName());
5197 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005198 Instruction *X =
5199 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5200 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005201 InsertNewInstBefore(X, I); // (X + (Y << C))
5202 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005203 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005204 return BinaryOperator::createAnd(X, C2);
5205 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005206
Chris Lattner150f12a2005-09-18 06:30:59 +00005207 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5208 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5209 match(Op0BO->getOperand(1),
5210 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005211 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005212 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005213 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005214 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005215 Op0BO->getName());
5216 InsertNewInstBefore(YS, I); // (Y << C)
5217 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005218 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005219 V1->getName()+".mask");
5220 InsertNewInstBefore(XM, I); // X & (CC << C)
5221
5222 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5223 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005224
Chris Lattner150f12a2005-09-18 06:30:59 +00005225 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00005226 case Instruction::Sub:
5227 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005228 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5229 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005230 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005231 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005232 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005233 Op0BO->getName());
5234 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005235 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005236 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005237 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005238 InsertNewInstBefore(X, I); // (X + (Y << C))
5239 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005240 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005241 return BinaryOperator::createAnd(X, C2);
5242 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005243
Chris Lattner13d4ab42006-05-31 21:14:00 +00005244 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005245 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5246 match(Op0BO->getOperand(0),
5247 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005248 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005249 cast<BinaryOperator>(Op0BO->getOperand(0))
5250 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005251 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005252 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005253 Op0BO->getName());
5254 InsertNewInstBefore(YS, I); // (Y << C)
5255 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005256 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005257 V1->getName()+".mask");
5258 InsertNewInstBefore(XM, I); // X & (CC << C)
5259
Chris Lattner13d4ab42006-05-31 21:14:00 +00005260 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005261 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005262
Chris Lattner11021cb2005-09-18 05:12:10 +00005263 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005264 }
5265
5266
5267 // If the operand is an bitwise operator with a constant RHS, and the
5268 // shift is the only use, we can pull it out of the shift.
5269 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5270 bool isValid = true; // Valid only for And, Or, Xor
5271 bool highBitSet = false; // Transform if high bit of constant set?
5272
5273 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005274 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005275 case Instruction::Add:
5276 isValid = isLeftShift;
5277 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005278 case Instruction::Or:
5279 case Instruction::Xor:
5280 highBitSet = false;
5281 break;
5282 case Instruction::And:
5283 highBitSet = true;
5284 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005285 }
5286
5287 // If this is a signed shift right, and the high bit is modified
5288 // by the logical operation, do not perform the transformation.
5289 // The highBitSet boolean indicates the value of the high bit of
5290 // the constant which would cause it to be modified for this
5291 // operation.
5292 //
Chris Lattner830ed032006-01-06 07:22:22 +00005293 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005294 uint64_t Val = Op0C->getZExtValue();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005295 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5296 }
5297
5298 if (isValid) {
5299 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5300
5301 Instruction *NewShift =
5302 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5303 Op0BO->getName());
5304 Op0BO->setName("");
5305 InsertNewInstBefore(NewShift, I);
5306
5307 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5308 NewRHS);
5309 }
5310 }
5311 }
5312 }
5313
Chris Lattnerad0124c2006-01-06 07:52:12 +00005314 // Find out if this is a shift of a shift by a constant.
5315 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005316 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00005317 ShiftOp = Op0SI;
Reid Spencer3da59db2006-11-27 01:05:10 +00005318 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5319 // If this is a noop-integer cast of a shift instruction, use the shift.
5320 if (isa<ShiftInst>(CI->getOperand(0))) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005321 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5322 }
5323 }
5324
Reid Spencerb83eb642006-10-20 07:07:24 +00005325 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005326 // Find the operands and properties of the input shift. Note that the
5327 // signedness of the input shift may differ from the current shift if there
5328 // is a noop cast between the two.
5329 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
Reid Spencer3822ff52006-11-08 06:47:33 +00005330 bool isShiftOfSignedShift = isShiftOfLeftShift ?
5331 ShiftOp->getType()->isSigned() :
5332 ShiftOp->getOpcode() == Instruction::AShr;
Chris Lattnere8d56c52006-01-07 01:32:28 +00005333 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005334
Reid Spencerb83eb642006-10-20 07:07:24 +00005335 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005336
Reid Spencerb83eb642006-10-20 07:07:24 +00005337 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5338 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnerad0124c2006-01-06 07:52:12 +00005339
5340 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5341 if (isLeftShift == isShiftOfLeftShift) {
5342 // Do not fold these shifts if the first one is signed and the second one
5343 // is unsigned and this is a right shift. Further, don't do any folding
5344 // on them.
5345 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5346 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005347
Chris Lattnerad0124c2006-01-06 07:52:12 +00005348 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5349 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5350 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005351
Chris Lattnerad0124c2006-01-06 07:52:12 +00005352 Value *Op = ShiftOp->getOperand(0);
5353 if (isShiftOfSignedShift != isSignedShift)
Reid Spencer3da59db2006-11-27 01:05:10 +00005354 Op = InsertNewInstBefore(
5355 CastInst::createInferredCast(Op, I.getType(), "tmp"), I);
5356 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
Reid Spencerb83eb642006-10-20 07:07:24 +00005357 ConstantInt::get(Type::UByteTy, Amt));
Reid Spencer3822ff52006-11-08 06:47:33 +00005358 if (I.getType() == ShiftResult->getType())
5359 return ShiftResult;
5360 InsertNewInstBefore(ShiftResult, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00005361 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00005362 }
5363
5364 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5365 // signed types, we can only support the (A >> c1) << c2 configuration,
5366 // because it can not turn an arbitrary bit of A into a sign bit.
5367 if (isUnsignedShift || isLeftShift) {
5368 // Calculate bitmask for what gets shifted off the edge.
5369 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5370 if (isLeftShift)
5371 C = ConstantExpr::getShl(C, ShiftAmt1C);
5372 else
Reid Spencer3822ff52006-11-08 06:47:33 +00005373 C = ConstantExpr::getLShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005374
5375 Value *Op = ShiftOp->getOperand(0);
Reid Spencer3822ff52006-11-08 06:47:33 +00005376 if (Op->getType() != C->getType())
Reid Spencer811b0cb2006-10-26 19:19:06 +00005377 Op = InsertCastBefore(Op, I.getType(), I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005378
5379 Instruction *Mask =
5380 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5381 InsertNewInstBefore(Mask, I);
5382
5383 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00005384 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005385 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00005386 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005387 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005388 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005389 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5390 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
Reid Spencer3822ff52006-11-08 06:47:33 +00005391 return new ShiftInst(Instruction::LShr, Mask,
5392 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005393 } else {
5394 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005395 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005396 }
5397 } else {
5398 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
Reid Spencer811b0cb2006-10-26 19:19:06 +00005399 Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
Chris Lattnere8d56c52006-01-07 01:32:28 +00005400 Instruction *Shift =
5401 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencerb83eb642006-10-20 07:07:24 +00005402 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005403 InsertNewInstBefore(Shift, I);
5404
5405 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5406 C = ConstantExpr::getShl(C, Op1);
5407 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5408 InsertNewInstBefore(Mask, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00005409 return CastInst::create(Instruction::BitCast, Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00005410 }
5411 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00005412 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00005413 // this case, C1 == C2 and C1 is 8, 16, or 32.
5414 if (ShiftAmt1 == ShiftAmt2) {
5415 const Type *SExtType = 0;
Chris Lattner94046b42006-04-28 22:21:41 +00005416 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005417 case 8 : SExtType = Type::SByteTy; break;
5418 case 16: SExtType = Type::ShortTy; break;
5419 case 32: SExtType = Type::IntTy; break;
5420 }
5421
5422 if (SExtType) {
Reid Spencer3da59db2006-11-27 01:05:10 +00005423 Instruction *NewTrunc =
5424 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
Chris Lattnerad0124c2006-01-06 07:52:12 +00005425 InsertNewInstBefore(NewTrunc, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00005426 return new SExtInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00005427 }
Chris Lattner11021cb2005-09-18 05:12:10 +00005428 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00005429 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00005430 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005431 return 0;
5432}
5433
Chris Lattnera1be5662002-05-02 17:06:02 +00005434
Chris Lattnercfd65102005-10-29 04:36:15 +00005435/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5436/// expression. If so, decompose it, returning some value X, such that Val is
5437/// X*Scale+Offset.
5438///
5439static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5440 unsigned &Offset) {
5441 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00005442 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5443 if (CI->getType()->isUnsigned()) {
5444 Offset = CI->getZExtValue();
5445 Scale = 1;
5446 return ConstantInt::get(Type::UIntTy, 0);
5447 }
Chris Lattnercfd65102005-10-29 04:36:15 +00005448 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5449 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005450 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5451 if (CUI->getType()->isUnsigned()) {
5452 if (I->getOpcode() == Instruction::Shl) {
5453 // This is a value scaled by '1 << the shift amt'.
5454 Scale = 1U << CUI->getZExtValue();
5455 Offset = 0;
5456 return I->getOperand(0);
5457 } else if (I->getOpcode() == Instruction::Mul) {
5458 // This value is scaled by 'CUI'.
5459 Scale = CUI->getZExtValue();
5460 Offset = 0;
5461 return I->getOperand(0);
5462 } else if (I->getOpcode() == Instruction::Add) {
5463 // We have X+C. Check to see if we really have (X*C2)+C1,
5464 // where C1 is divisible by C2.
5465 unsigned SubScale;
5466 Value *SubVal =
5467 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5468 Offset += CUI->getZExtValue();
5469 if (SubScale > 1 && (Offset % SubScale == 0)) {
5470 Scale = SubScale;
5471 return SubVal;
5472 }
Chris Lattnercfd65102005-10-29 04:36:15 +00005473 }
5474 }
5475 }
5476 }
5477 }
5478
5479 // Otherwise, we can't look past this.
5480 Scale = 1;
5481 Offset = 0;
5482 return Val;
5483}
5484
5485
Chris Lattnerb3f83972005-10-24 06:03:58 +00005486/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5487/// try to eliminate the cast by moving the type information into the alloc.
5488Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5489 AllocationInst &AI) {
5490 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005491 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00005492
Chris Lattnerb53c2382005-10-24 06:22:12 +00005493 // Remove any uses of AI that are dead.
5494 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5495 std::vector<Instruction*> DeadUsers;
5496 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5497 Instruction *User = cast<Instruction>(*UI++);
5498 if (isInstructionTriviallyDead(User)) {
5499 while (UI != E && *UI == User)
5500 ++UI; // If this instruction uses AI more than once, don't break UI.
5501
5502 // Add operands to the worklist.
5503 AddUsesToWorkList(*User);
5504 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00005505 DOUT << "IC: DCE: " << *User;
Chris Lattnerb53c2382005-10-24 06:22:12 +00005506
5507 User->eraseFromParent();
5508 removeFromWorkList(User);
5509 }
5510 }
5511
Chris Lattnerb3f83972005-10-24 06:03:58 +00005512 // Get the type really allocated and the type casted to.
5513 const Type *AllocElTy = AI.getAllocatedType();
5514 const Type *CastElTy = PTy->getElementType();
5515 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005516
Chris Lattnere831b9a2006-10-01 19:40:58 +00005517 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5518 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00005519 if (CastElTyAlign < AllocElTyAlign) return 0;
5520
Chris Lattner39387a52005-10-24 06:35:18 +00005521 // If the allocation has multiple uses, only promote it if we are strictly
5522 // increasing the alignment of the resultant allocation. If we keep it the
5523 // same, we open the door to infinite loops of various kinds.
5524 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5525
Chris Lattnerb3f83972005-10-24 06:03:58 +00005526 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5527 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005528 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005529
Chris Lattner455fcc82005-10-29 03:19:53 +00005530 // See if we can satisfy the modulus by pulling a scale out of the array
5531 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00005532 unsigned ArraySizeScale, ArrayOffset;
5533 Value *NumElements = // See if the array size is a decomposable linear expr.
5534 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5535
Chris Lattner455fcc82005-10-29 03:19:53 +00005536 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5537 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00005538 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5539 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00005540
Chris Lattner455fcc82005-10-29 03:19:53 +00005541 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5542 Value *Amt = 0;
5543 if (Scale == 1) {
5544 Amt = NumElements;
5545 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00005546 // If the allocation size is constant, form a constant mul expression
5547 Amt = ConstantInt::get(Type::UIntTy, Scale);
5548 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5549 Amt = ConstantExpr::getMul(
5550 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5551 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00005552 else if (Scale != 1) {
5553 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5554 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00005555 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005556 }
5557
Chris Lattnercfd65102005-10-29 04:36:15 +00005558 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005559 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattnercfd65102005-10-29 04:36:15 +00005560 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5561 Amt = InsertNewInstBefore(Tmp, AI);
5562 }
5563
Chris Lattnerb3f83972005-10-24 06:03:58 +00005564 std::string Name = AI.getName(); AI.setName("");
5565 AllocationInst *New;
5566 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00005567 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005568 else
Nate Begeman14b05292005-11-05 09:21:28 +00005569 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005570 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00005571
5572 // If the allocation has multiple uses, insert a cast and change all things
5573 // that used it to use the new cast. This will also hack on CI, but it will
5574 // die soon.
5575 if (!AI.hasOneUse()) {
5576 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00005577 // New is the allocation instruction, pointer typed. AI is the original
5578 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5579 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00005580 InsertNewInstBefore(NewCast, AI);
5581 AI.replaceAllUsesWith(NewCast);
5582 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00005583 return ReplaceInstUsesWith(CI, New);
5584}
5585
Chris Lattner70074e02006-05-13 02:06:03 +00005586/// CanEvaluateInDifferentType - Return true if we can take the specified value
5587/// and return it without inserting any new casts. This is used by code that
5588/// tries to decide whether promoting or shrinking integer operations to wider
5589/// or smaller types will allow us to eliminate a truncate or extend.
5590static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5591 int &NumCastsRemoved) {
5592 if (isa<Constant>(V)) return true;
5593
5594 Instruction *I = dyn_cast<Instruction>(V);
5595 if (!I || !I->hasOneUse()) return false;
5596
5597 switch (I->getOpcode()) {
5598 case Instruction::And:
5599 case Instruction::Or:
5600 case Instruction::Xor:
5601 // These operators can all arbitrarily be extended or truncated.
5602 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5603 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
Reid Spencer3da59db2006-11-27 01:05:10 +00005604 case Instruction::Trunc:
5605 case Instruction::ZExt:
5606 case Instruction::SExt:
5607 case Instruction::BitCast:
Chris Lattner70074e02006-05-13 02:06:03 +00005608 // If this is a cast from the destination type, we can trivially eliminate
5609 // it, and this will remove a cast overall.
5610 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00005611 // If the first operand is itself a cast, and is eliminable, do not count
5612 // this as an eliminable cast. We would prefer to eliminate those two
5613 // casts first.
Reid Spencer3ed469c2006-11-02 20:25:50 +00005614 if (isa<CastInst>(I->getOperand(0)))
Chris Lattnerd2280182006-06-28 17:34:50 +00005615 return true;
5616
Chris Lattner70074e02006-05-13 02:06:03 +00005617 ++NumCastsRemoved;
5618 return true;
5619 }
Reid Spencer3da59db2006-11-27 01:05:10 +00005620 break;
5621 default:
Chris Lattner70074e02006-05-13 02:06:03 +00005622 // TODO: Can handle more cases here.
5623 break;
5624 }
5625
5626 return false;
5627}
5628
5629/// EvaluateInDifferentType - Given an expression that
5630/// CanEvaluateInDifferentType returns true for, actually insert the code to
5631/// evaluate the expression.
5632Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5633 if (Constant *C = dyn_cast<Constant>(V))
5634 return ConstantExpr::getCast(C, Ty);
5635
5636 // Otherwise, it must be an instruction.
5637 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00005638 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00005639 switch (I->getOpcode()) {
5640 case Instruction::And:
5641 case Instruction::Or:
5642 case Instruction::Xor: {
5643 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5644 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5645 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5646 LHS, RHS, I->getName());
5647 break;
5648 }
Reid Spencer3da59db2006-11-27 01:05:10 +00005649 case Instruction::Trunc:
5650 case Instruction::ZExt:
5651 case Instruction::SExt:
5652 case Instruction::BitCast:
5653 // If the source type of the cast is the type we're trying for then we can
5654 // just return the source. There's no need to insert it because its not new.
Chris Lattner70074e02006-05-13 02:06:03 +00005655 if (I->getOperand(0)->getType() == Ty)
5656 return I->getOperand(0);
5657
Reid Spencer3da59db2006-11-27 01:05:10 +00005658 // Some other kind of cast, which shouldn't happen, so just ..
5659 // FALL THROUGH
5660 default:
Chris Lattner70074e02006-05-13 02:06:03 +00005661 // TODO: Can handle more cases here.
5662 assert(0 && "Unreachable!");
5663 break;
5664 }
5665
5666 return InsertNewInstBefore(Res, *I);
5667}
5668
Reid Spencer3da59db2006-11-27 01:05:10 +00005669/// @brief Implement the transforms common to all CastInst visitors.
5670Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00005671 Value *Src = CI.getOperand(0);
5672
Reid Spencer3da59db2006-11-27 01:05:10 +00005673 // Casting undef to anything results in undef so might as just replace it and
5674 // get rid of the cast.
Chris Lattnere87597f2004-10-16 18:11:37 +00005675 if (isa<UndefValue>(Src)) // cast undef -> undef
5676 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5677
Reid Spencer3da59db2006-11-27 01:05:10 +00005678 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5679 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00005680 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00005681 if (Instruction::CastOps opc =
5682 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5683 // The first cast (CSrc) is eliminable so we need to fix up or replace
5684 // the second cast (CI). CSrc will then have a good chance of being dead.
5685 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00005686 }
5687 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00005688
Chris Lattner797249b2003-06-21 23:12:02 +00005689 // If casting the result of a getelementptr instruction with no offset, turn
5690 // this into a cast of the original pointer!
5691 //
Chris Lattner79d35b32003-06-23 21:59:52 +00005692 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00005693 bool AllZeroOperands = true;
5694 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5695 if (!isa<Constant>(GEP->getOperand(i)) ||
5696 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5697 AllZeroOperands = false;
5698 break;
5699 }
5700 if (AllZeroOperands) {
Reid Spencer3da59db2006-11-27 01:05:10 +00005701 // Changing the cast operand is usually not a good idea but it is safe
5702 // here because the pointer operand is being replaced with another
5703 // pointer operand so the opcode doesn't need to change.
Chris Lattner797249b2003-06-21 23:12:02 +00005704 CI.setOperand(0, GEP->getOperand(0));
5705 return &CI;
5706 }
5707 }
Chris Lattner13c654a2006-11-21 17:05:13 +00005708
Chris Lattnerbc61e662003-11-02 05:57:39 +00005709 // If we are casting a malloc or alloca to a pointer to a type of the same
5710 // size, rewrite the allocation instruction to allocate the "right" type.
Chris Lattnerbc61e662003-11-02 05:57:39 +00005711 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00005712 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5713 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005714
Reid Spencer3da59db2006-11-27 01:05:10 +00005715 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00005716 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5717 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5718 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00005719
5720 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00005721 if (isa<PHINode>(Src))
5722 if (Instruction *NV = FoldOpIntoPhi(CI))
5723 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00005724
Reid Spencer3da59db2006-11-27 01:05:10 +00005725 return 0;
5726}
5727
5728/// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5729/// integers. This function implements the common transforms for all those
5730/// cases.
5731/// @brief Implement the transforms common to CastInst with integer operands
5732Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5733 if (Instruction *Result = commonCastTransforms(CI))
5734 return Result;
5735
5736 Value *Src = CI.getOperand(0);
5737 const Type *SrcTy = Src->getType();
5738 const Type *DestTy = CI.getType();
5739 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5740 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5741
5742 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
5743 // because codegen cannot accurately perform a truncate to bool operation.
5744 // Something goes wrong in promotion to a larger type. When CodeGen can
5745 // handle a proper truncation to bool, this should be removed.
5746 if (DestTy == Type::BoolTy)
5747 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
5748
5749 // See if we can simplify any instructions used by the LHS whose sole
5750 // purpose is to compute bits we don't care about.
5751 uint64_t KnownZero = 0, KnownOne = 0;
5752 if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5753 KnownZero, KnownOne))
5754 return &CI;
5755
5756 // If the source isn't an instruction or has more than one use then we
5757 // can't do anything more.
5758 if (!isa<Instruction>(Src) || !Src->hasOneUse())
5759 return 0;
5760
5761 // Attempt to propagate the cast into the instruction.
5762 Instruction *SrcI = cast<Instruction>(Src);
5763 int NumCastsRemoved = 0;
5764 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5765 // If this cast is a truncate, evaluting in a different type always
5766 // eliminates the cast, so it is always a win. If this is a noop-cast
5767 // this just removes a noop cast which isn't pointful, but simplifies
5768 // the code. If this is a zero-extension, we need to do an AND to
5769 // maintain the clear top-part of the computation, so we require that
5770 // the input have eliminated at least one cast. If this is a sign
5771 // extension, we insert two new casts (to do the extension) so we
5772 // require that two casts have been eliminated.
5773 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5774 if (!DoXForm) {
5775 switch (CI.getOpcode()) {
5776 case Instruction::Trunc:
5777 DoXForm = true;
5778 break;
5779 case Instruction::ZExt:
5780 DoXForm = NumCastsRemoved >= 1;
5781 break;
5782 case Instruction::SExt:
5783 DoXForm = NumCastsRemoved >= 2;
5784 break;
5785 case Instruction::BitCast:
5786 DoXForm = false;
5787 break;
5788 default:
5789 // All the others use floating point so we shouldn't actually
5790 // get here because of the check above.
5791 assert(!"Unknown cast type .. unreachable");
5792 break;
5793 }
5794 }
5795
5796 if (DoXForm) {
5797 Value *Res = EvaluateInDifferentType(SrcI, DestTy);
5798 assert(Res->getType() == DestTy);
5799 switch (CI.getOpcode()) {
5800 default: assert(0 && "Unknown cast type!");
5801 case Instruction::Trunc:
5802 case Instruction::BitCast:
5803 // Just replace this cast with the result.
5804 return ReplaceInstUsesWith(CI, Res);
5805 case Instruction::ZExt: {
5806 // We need to emit an AND to clear the high bits.
5807 assert(SrcBitSize < DestBitSize && "Not a zext?");
5808 Constant *C =
5809 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5810 if (DestBitSize < 64)
5811 C = ConstantExpr::getTrunc(C, DestTy);
5812 else {
5813 assert(DestBitSize == 64);
5814 C = ConstantExpr::getBitCast(C, DestTy);
5815 }
5816 return BinaryOperator::createAnd(Res, C);
5817 }
5818 case Instruction::SExt:
5819 // We need to emit a cast to truncate, then a cast to sext.
5820 return CastInst::create(Instruction::SExt,
5821 InsertCastBefore(Res, Src->getType(), CI), DestTy);
5822 }
5823 }
5824 }
5825
5826 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5827 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5828
5829 switch (SrcI->getOpcode()) {
5830 case Instruction::Add:
5831 case Instruction::Mul:
5832 case Instruction::And:
5833 case Instruction::Or:
5834 case Instruction::Xor:
5835 // If we are discarding information, or just changing the sign,
5836 // rewrite.
5837 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5838 // Don't insert two casts if they cannot be eliminated. We allow
5839 // two casts to be inserted if the sizes are the same. This could
5840 // only be converting signedness, which is a noop.
5841 if (DestBitSize == SrcBitSize ||
5842 !ValueRequiresCast(Op1, DestTy,TD) ||
5843 !ValueRequiresCast(Op0, DestTy, TD)) {
5844 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5845 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5846 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5847 ->getOpcode(), Op0c, Op1c);
5848 }
5849 }
5850
5851 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5852 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
5853 SrcI->getOpcode() == Instruction::Xor &&
5854 Op1 == ConstantBool::getTrue() &&
5855 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5856 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5857 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5858 }
5859 break;
5860 case Instruction::SDiv:
5861 case Instruction::UDiv:
5862 case Instruction::SRem:
5863 case Instruction::URem:
5864 // If we are just changing the sign, rewrite.
5865 if (DestBitSize == SrcBitSize) {
5866 // Don't insert two casts if they cannot be eliminated. We allow
5867 // two casts to be inserted if the sizes are the same. This could
5868 // only be converting signedness, which is a noop.
5869 if (!ValueRequiresCast(Op1, DestTy,TD) ||
5870 !ValueRequiresCast(Op0, DestTy, TD)) {
5871 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5872 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5873 return BinaryOperator::create(
5874 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5875 }
5876 }
5877 break;
5878
5879 case Instruction::Shl:
5880 // Allow changing the sign of the source operand. Do not allow
5881 // changing the size of the shift, UNLESS the shift amount is a
5882 // constant. We must not change variable sized shifts to a smaller
5883 // size, because it is undefined to shift more bits out than exist
5884 // in the value.
5885 if (DestBitSize == SrcBitSize ||
5886 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5887 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5888 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5889 }
5890 break;
5891 case Instruction::AShr:
5892 // If this is a signed shr, and if all bits shifted in are about to be
5893 // truncated off, turn it into an unsigned shr to allow greater
5894 // simplifications.
5895 if (DestBitSize < SrcBitSize &&
5896 isa<ConstantInt>(Op1)) {
5897 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5898 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5899 // Insert the new logical shift right.
5900 return new ShiftInst(Instruction::LShr, Op0, Op1);
5901 }
5902 }
5903 break;
5904
5905 case Instruction::SetEQ:
5906 case Instruction::SetNE:
5907 // If we are just checking for a seteq of a single bit and casting it
5908 // to an integer. If so, shift the bit to the appropriate place then
5909 // cast to integer to avoid the comparison.
5910 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5911 uint64_t Op1CV = Op1C->getZExtValue();
5912 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5913 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5914 // cast (X == 1) to int --> X iff X has only the low bit set.
5915 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5916 // cast (X != 0) to int --> X iff X has only the low bit set.
5917 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5918 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5919 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5920 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5921 // If Op1C some other power of two, convert:
5922 uint64_t KnownZero, KnownOne;
5923 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5924 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5925
5926 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5927 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5928 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5929 // (X&4) == 2 --> false
5930 // (X&4) != 2 --> true
5931 Constant *Res = ConstantBool::get(isSetNE);
5932 Res = ConstantExpr::getZeroExtend(Res, CI.getType());
5933 return ReplaceInstUsesWith(CI, Res);
5934 }
5935
5936 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5937 Value *In = Op0;
5938 if (ShiftAmt) {
5939 // Perform a logical shr by shiftamt.
5940 // Insert the shift to put the result in the low bit.
5941 In = InsertNewInstBefore(
5942 new ShiftInst(Instruction::LShr, In,
5943 ConstantInt::get(Type::UByteTy, ShiftAmt),
5944 In->getName()+".lobit"), CI);
5945 }
5946
5947 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5948 Constant *One = ConstantInt::get(In->getType(), 1);
5949 In = BinaryOperator::createXor(In, One, "tmp");
5950 InsertNewInstBefore(cast<Instruction>(In), CI);
5951 }
5952
5953 if (CI.getType() == In->getType())
5954 return ReplaceInstUsesWith(CI, In);
5955 else
5956 return CastInst::createInferredCast(In, CI.getType());
5957 }
5958 }
5959 }
5960 break;
5961 }
5962 return 0;
5963}
5964
5965Instruction *InstCombiner::visitTrunc(CastInst &CI) {
5966 return commonIntCastTransforms(CI);
5967}
5968
5969Instruction *InstCombiner::visitZExt(CastInst &CI) {
5970 // If one of the common conversion will work ..
5971 if (Instruction *Result = commonIntCastTransforms(CI))
5972 return Result;
5973
5974 Value *Src = CI.getOperand(0);
5975
5976 // If this is a cast of a cast
5977 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5978 // If the operand of the ZEXT is a TRUNC then we are dealing with integral
5979 // types and we can convert this to a logical AND if the sizes are just
5980 // right. This will be much cheaper than the pair of casts.
5981 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
5982 // types and if the sizes are just right we can convert this into a logical
5983 // 'and' which will be much cheaper than the pair of casts.
5984 if (isa<TruncInst>(CSrc)) {
5985 // Get the sizes of the types involved
5986 Value *A = CSrc->getOperand(0);
5987 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
5988 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
5989 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
5990 // If we're actually extending zero bits and the trunc is a no-op
5991 if (MidSize < DstSize && SrcSize == DstSize) {
5992 // Replace both of the casts with an And of the type mask.
5993 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5994 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
5995 Instruction *And =
5996 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
5997 // Unfortunately, if the type changed, we need to cast it back.
5998 if (And->getType() != CI.getType()) {
5999 And->setName(CSrc->getName()+".mask");
6000 InsertNewInstBefore(And, CI);
6001 And = CastInst::createInferredCast(And, CI.getType());
6002 }
6003 return And;
6004 }
6005 }
6006 }
6007
6008 return 0;
6009}
6010
6011Instruction *InstCombiner::visitSExt(CastInst &CI) {
6012 return commonIntCastTransforms(CI);
6013}
6014
6015Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6016 return commonCastTransforms(CI);
6017}
6018
6019Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6020 return commonCastTransforms(CI);
6021}
6022
6023Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6024 if (Instruction *I = commonCastTransforms(CI))
6025 return I;
6026
6027 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
6028 // because codegen cannot accurately perform a truncate to bool operation.
6029 // Something goes wrong in promotion to a larger type. When CodeGen can
6030 // handle a proper truncation to bool, this should be removed.
6031 Value *Src = CI.getOperand(0);
6032 const Type *SrcTy = Src->getType();
6033 const Type *DestTy = CI.getType();
6034 if (DestTy == Type::BoolTy)
6035 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
6036 return 0;
6037}
6038
6039Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6040 if (Instruction *I = commonCastTransforms(CI))
6041 return I;
6042
6043 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
6044 // because codegen cannot accurately perform a truncate to bool operation.
6045 // Something goes wrong in promotion to a larger type. When CodeGen can
6046 // handle a proper truncation to bool, this should be removed.
6047 Value *Src = CI.getOperand(0);
6048 const Type *SrcTy = Src->getType();
6049 const Type *DestTy = CI.getType();
6050 if (DestTy == Type::BoolTy)
6051 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
6052 return 0;
6053}
6054
6055Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6056 return commonCastTransforms(CI);
6057}
6058
6059Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6060 return commonCastTransforms(CI);
6061}
6062
6063Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6064 if (Instruction *I = commonCastTransforms(CI))
6065 return I;
6066
6067 // FIXME. We currently implement cast-to-bool as a setne %X, 0. This is
6068 // because codegen cannot accurately perform a truncate to bool operation.
6069 // Something goes wrong in promotion to a larger type. When CodeGen can
6070 // handle a proper truncation to bool, this should be removed.
6071 Value *Src = CI.getOperand(0);
6072 const Type *SrcTy = Src->getType();
6073 const Type *DestTy = CI.getType();
6074 if (DestTy == Type::BoolTy)
6075 return BinaryOperator::createSetNE(Src, Constant::getNullValue(SrcTy));
6076 return 0;
6077}
6078
6079Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6080 return commonCastTransforms(CI);
6081}
6082
6083Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6084
6085 // If the operands are integer typed then apply the integer transforms,
6086 // otherwise just apply the common ones.
6087 Value *Src = CI.getOperand(0);
6088 const Type *SrcTy = Src->getType();
6089 const Type *DestTy = CI.getType();
6090
6091 if (SrcTy->isInteger() && DestTy->isInteger()) {
6092 if (Instruction *Result = commonIntCastTransforms(CI))
6093 return Result;
6094 } else {
6095 if (Instruction *Result = commonCastTransforms(CI))
6096 return Result;
6097 }
6098
6099
6100 // Get rid of casts from one type to the same type. These are useless and can
6101 // be replaced by the operand.
6102 if (DestTy == Src->getType())
6103 return ReplaceInstUsesWith(CI, Src);
6104
Chris Lattner9fb92132006-04-12 18:09:35 +00006105 // If the source and destination are pointers, and this cast is equivalent to
6106 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6107 // This can enhance SROA and other transforms that want type-safe pointers.
Reid Spencer3da59db2006-11-27 01:05:10 +00006108 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6109 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6110 const Type *DstElTy = DstPTy->getElementType();
6111 const Type *SrcElTy = SrcPTy->getElementType();
Chris Lattner9fb92132006-04-12 18:09:35 +00006112
6113 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6114 unsigned NumZeros = 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00006115 while (SrcElTy != DstElTy &&
6116 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6117 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6118 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
Chris Lattner9fb92132006-04-12 18:09:35 +00006119 ++NumZeros;
6120 }
Chris Lattner4e998b22004-09-29 05:07:12 +00006121
Chris Lattner9fb92132006-04-12 18:09:35 +00006122 // If we found a path from the src to dest, create the getelementptr now.
Reid Spencer3da59db2006-11-27 01:05:10 +00006123 if (SrcElTy == DstElTy) {
Chris Lattner9fb92132006-04-12 18:09:35 +00006124 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6125 return new GetElementPtrInst(Src, Idxs);
6126 }
6127 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006128 }
Chris Lattner24c8e382003-07-24 17:35:25 +00006129
Reid Spencer3da59db2006-11-27 01:05:10 +00006130 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6131 if (SVI->hasOneUse()) {
6132 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6133 // a bitconvert to a vector with the same # elts.
6134 if (isa<PackedType>(DestTy) &&
6135 cast<PackedType>(DestTy)->getNumElements() ==
6136 SVI->getType()->getNumElements()) {
6137 CastInst *Tmp;
6138 // If either of the operands is a cast from CI.getType(), then
6139 // evaluating the shuffle in the casted destination's type will allow
6140 // us to eliminate at least one cast.
6141 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6142 Tmp->getOperand(0)->getType() == DestTy) ||
6143 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6144 Tmp->getOperand(0)->getType() == DestTy)) {
6145 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0), DestTy, &CI);
6146 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1), DestTy, &CI);
6147 // Return a new shuffle vector. Use the same element ID's, as we
6148 // know the vector types match #elts.
6149 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00006150 }
6151 }
6152 }
6153 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00006154 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00006155}
6156
Chris Lattnere576b912004-04-09 23:46:01 +00006157/// GetSelectFoldableOperands - We want to turn code that looks like this:
6158/// %C = or %A, %B
6159/// %D = select %cond, %C, %A
6160/// into:
6161/// %C = select %cond, %B, 0
6162/// %D = or %A, %C
6163///
6164/// Assuming that the specified instruction is an operand to the select, return
6165/// a bitmask indicating which operands of this instruction are foldable if they
6166/// equal the other incoming value of the select.
6167///
6168static unsigned GetSelectFoldableOperands(Instruction *I) {
6169 switch (I->getOpcode()) {
6170 case Instruction::Add:
6171 case Instruction::Mul:
6172 case Instruction::And:
6173 case Instruction::Or:
6174 case Instruction::Xor:
6175 return 3; // Can fold through either operand.
6176 case Instruction::Sub: // Can only fold on the amount subtracted.
6177 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00006178 case Instruction::LShr:
6179 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00006180 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00006181 default:
6182 return 0; // Cannot fold
6183 }
6184}
6185
6186/// GetSelectFoldableConstant - For the same transformation as the previous
6187/// function, return the identity constant that goes into the select.
6188static Constant *GetSelectFoldableConstant(Instruction *I) {
6189 switch (I->getOpcode()) {
6190 default: assert(0 && "This cannot happen!"); abort();
6191 case Instruction::Add:
6192 case Instruction::Sub:
6193 case Instruction::Or:
6194 case Instruction::Xor:
6195 return Constant::getNullValue(I->getType());
6196 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00006197 case Instruction::LShr:
6198 case Instruction::AShr:
Chris Lattnere576b912004-04-09 23:46:01 +00006199 return Constant::getNullValue(Type::UByteTy);
6200 case Instruction::And:
6201 return ConstantInt::getAllOnesValue(I->getType());
6202 case Instruction::Mul:
6203 return ConstantInt::get(I->getType(), 1);
6204 }
6205}
6206
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006207/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6208/// have the same opcode and only one use each. Try to simplify this.
6209Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6210 Instruction *FI) {
6211 if (TI->getNumOperands() == 1) {
6212 // If this is a non-volatile load or a cast from the same type,
6213 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00006214 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006215 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6216 return 0;
6217 } else {
6218 return 0; // unknown unary op.
6219 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006220
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006221 // Fold this by inserting a select from the input values.
6222 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6223 FI->getOperand(0), SI.getName()+".v");
6224 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006225 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6226 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006227 }
6228
6229 // Only handle binary operators here.
6230 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6231 return 0;
6232
6233 // Figure out if the operations have any operands in common.
6234 Value *MatchOp, *OtherOpT, *OtherOpF;
6235 bool MatchIsOpZero;
6236 if (TI->getOperand(0) == FI->getOperand(0)) {
6237 MatchOp = TI->getOperand(0);
6238 OtherOpT = TI->getOperand(1);
6239 OtherOpF = FI->getOperand(1);
6240 MatchIsOpZero = true;
6241 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6242 MatchOp = TI->getOperand(1);
6243 OtherOpT = TI->getOperand(0);
6244 OtherOpF = FI->getOperand(0);
6245 MatchIsOpZero = false;
6246 } else if (!TI->isCommutative()) {
6247 return 0;
6248 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6249 MatchOp = TI->getOperand(0);
6250 OtherOpT = TI->getOperand(1);
6251 OtherOpF = FI->getOperand(0);
6252 MatchIsOpZero = true;
6253 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6254 MatchOp = TI->getOperand(1);
6255 OtherOpT = TI->getOperand(0);
6256 OtherOpF = FI->getOperand(1);
6257 MatchIsOpZero = true;
6258 } else {
6259 return 0;
6260 }
6261
6262 // If we reach here, they do have operations in common.
6263 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6264 OtherOpF, SI.getName()+".v");
6265 InsertNewInstBefore(NewSI, SI);
6266
6267 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6268 if (MatchIsOpZero)
6269 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6270 else
6271 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6272 } else {
6273 if (MatchIsOpZero)
6274 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6275 else
6276 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6277 }
6278}
6279
Chris Lattner3d69f462004-03-12 05:52:32 +00006280Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006281 Value *CondVal = SI.getCondition();
6282 Value *TrueVal = SI.getTrueValue();
6283 Value *FalseVal = SI.getFalseValue();
6284
6285 // select true, X, Y -> X
6286 // select false, X, Y -> Y
6287 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner47811b72006-09-28 23:35:22 +00006288 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006289
6290 // select C, X, X -> X
6291 if (TrueVal == FalseVal)
6292 return ReplaceInstUsesWith(SI, TrueVal);
6293
Chris Lattnere87597f2004-10-16 18:11:37 +00006294 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6295 return ReplaceInstUsesWith(SI, FalseVal);
6296 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6297 return ReplaceInstUsesWith(SI, TrueVal);
6298 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6299 if (isa<Constant>(TrueVal))
6300 return ReplaceInstUsesWith(SI, TrueVal);
6301 else
6302 return ReplaceInstUsesWith(SI, FalseVal);
6303 }
6304
Chris Lattner0c199a72004-04-08 04:43:23 +00006305 if (SI.getType() == Type::BoolTy)
6306 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00006307 if (C->getValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006308 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006309 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006310 } else {
6311 // Change: A = select B, false, C --> A = and !B, C
6312 Value *NotCond =
6313 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6314 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006315 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006316 }
6317 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00006318 if (C->getValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00006319 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00006320 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006321 } else {
6322 // Change: A = select B, C, true --> A = or !B, C
6323 Value *NotCond =
6324 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6325 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00006326 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00006327 }
6328 }
6329
Chris Lattner2eefe512004-04-09 19:05:30 +00006330 // Selecting between two integer constants?
6331 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6332 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6333 // select C, 1, 0 -> cast C to int
Reid Spencerb83eb642006-10-20 07:07:24 +00006334 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006335 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencerb83eb642006-10-20 07:07:24 +00006336 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00006337 // select C, 0, 1 -> cast !C to int
6338 Value *NotCond =
6339 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00006340 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006341 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00006342 }
Chris Lattner457dd822004-06-09 07:59:58 +00006343
Chris Lattnerb8456462006-09-20 04:44:59 +00006344 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6345
6346 // (x <s 0) ? -1 : 0 -> sra x, 31
6347 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6348 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6349 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6350 bool CanXForm = false;
6351 if (CmpCst->getType()->isSigned())
6352 CanXForm = CmpCst->isNullValue() &&
6353 IC->getOpcode() == Instruction::SetLT;
6354 else {
6355 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006356 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattnerb8456462006-09-20 04:44:59 +00006357 IC->getOpcode() == Instruction::SetGT;
6358 }
6359
6360 if (CanXForm) {
6361 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00006362 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00006363 Value *X = IC->getOperand(0);
Chris Lattnerb8456462006-09-20 04:44:59 +00006364 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006365 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Reid Spencer3822ff52006-11-08 06:47:33 +00006366 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
Chris Lattnerb8456462006-09-20 04:44:59 +00006367 ShAmt, "ones");
6368 InsertNewInstBefore(SRA, SI);
6369
Reid Spencer3da59db2006-11-27 01:05:10 +00006370 // Finally, convert to the type of the select RHS. We figure out
6371 // if this requires a SExt, Trunc or BitCast based on the sizes.
6372 Instruction::CastOps opc = Instruction::BitCast;
6373 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6374 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6375 if (SRASize < SISize)
6376 opc = Instruction::SExt;
6377 else if (SRASize > SISize)
6378 opc = Instruction::Trunc;
6379 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00006380 }
6381 }
6382
6383
6384 // If one of the constants is zero (we know they can't both be) and we
6385 // have a setcc instruction with zero, and we have an 'and' with the
6386 // non-constant value, eliminate this whole mess. This corresponds to
6387 // cases like this: ((X & 27) ? 27 : 0)
6388 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattner65b72ba2006-09-18 04:22:48 +00006389 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006390 cast<Constant>(IC->getOperand(1))->isNullValue())
6391 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6392 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006393 isa<ConstantInt>(ICA->getOperand(1)) &&
6394 (ICA->getOperand(1) == TrueValC ||
6395 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006396 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6397 // Okay, now we know that everything is set up, we just don't
6398 // know whether we have a setne or seteq and whether the true or
6399 // false val is the zero.
6400 bool ShouldNotVal = !TrueValC->isNullValue();
6401 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6402 Value *V = ICA;
6403 if (ShouldNotVal)
6404 V = InsertNewInstBefore(BinaryOperator::create(
6405 Instruction::Xor, V, ICA->getOperand(1)), SI);
6406 return ReplaceInstUsesWith(SI, V);
6407 }
Chris Lattnerb8456462006-09-20 04:44:59 +00006408 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006409 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006410
6411 // See if we are selecting two values based on a comparison of the two values.
6412 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6413 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6414 // Transform (X == Y) ? X : Y -> Y
6415 if (SCI->getOpcode() == Instruction::SetEQ)
6416 return ReplaceInstUsesWith(SI, FalseVal);
6417 // Transform (X != Y) ? X : Y -> X
6418 if (SCI->getOpcode() == Instruction::SetNE)
6419 return ReplaceInstUsesWith(SI, TrueVal);
6420 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6421
6422 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6423 // Transform (X == Y) ? Y : X -> X
6424 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00006425 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006426 // Transform (X != Y) ? Y : X -> Y
6427 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00006428 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006429 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6430 }
6431 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006432
Chris Lattner87875da2005-01-13 22:52:24 +00006433 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6434 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6435 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00006436 Instruction *AddOp = 0, *SubOp = 0;
6437
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006438 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6439 if (TI->getOpcode() == FI->getOpcode())
6440 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6441 return IV;
6442
6443 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6444 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00006445 if (TI->getOpcode() == Instruction::Sub &&
6446 FI->getOpcode() == Instruction::Add) {
6447 AddOp = FI; SubOp = TI;
6448 } else if (FI->getOpcode() == Instruction::Sub &&
6449 TI->getOpcode() == Instruction::Add) {
6450 AddOp = TI; SubOp = FI;
6451 }
6452
6453 if (AddOp) {
6454 Value *OtherAddOp = 0;
6455 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6456 OtherAddOp = AddOp->getOperand(1);
6457 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6458 OtherAddOp = AddOp->getOperand(0);
6459 }
6460
6461 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00006462 // So at this point we know we have (Y -> OtherAddOp):
6463 // select C, (add X, Y), (sub X, Z)
6464 Value *NegVal; // Compute -Z
6465 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6466 NegVal = ConstantExpr::getNeg(C);
6467 } else {
6468 NegVal = InsertNewInstBefore(
6469 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00006470 }
Chris Lattner97f37a42006-02-24 18:05:58 +00006471
6472 Value *NewTrueOp = OtherAddOp;
6473 Value *NewFalseOp = NegVal;
6474 if (AddOp != TI)
6475 std::swap(NewTrueOp, NewFalseOp);
6476 Instruction *NewSel =
6477 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6478
6479 NewSel = InsertNewInstBefore(NewSel, SI);
6480 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00006481 }
6482 }
6483 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006484
Chris Lattnere576b912004-04-09 23:46:01 +00006485 // See if we can fold the select into one of our operands.
6486 if (SI.getType()->isInteger()) {
6487 // See the comment above GetSelectFoldableOperands for a description of the
6488 // transformation we are doing here.
6489 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6490 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6491 !isa<Constant>(FalseVal))
6492 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6493 unsigned OpToFold = 0;
6494 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6495 OpToFold = 1;
6496 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6497 OpToFold = 2;
6498 }
6499
6500 if (OpToFold) {
6501 Constant *C = GetSelectFoldableConstant(TVI);
6502 std::string Name = TVI->getName(); TVI->setName("");
6503 Instruction *NewSel =
6504 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6505 Name);
6506 InsertNewInstBefore(NewSel, SI);
6507 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6508 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6509 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6510 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6511 else {
6512 assert(0 && "Unknown instruction!!");
6513 }
6514 }
6515 }
Chris Lattnera96879a2004-09-29 17:40:11 +00006516
Chris Lattnere576b912004-04-09 23:46:01 +00006517 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6518 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6519 !isa<Constant>(TrueVal))
6520 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6521 unsigned OpToFold = 0;
6522 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6523 OpToFold = 1;
6524 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6525 OpToFold = 2;
6526 }
6527
6528 if (OpToFold) {
6529 Constant *C = GetSelectFoldableConstant(FVI);
6530 std::string Name = FVI->getName(); FVI->setName("");
6531 Instruction *NewSel =
6532 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6533 Name);
6534 InsertNewInstBefore(NewSel, SI);
6535 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6536 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6537 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6538 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6539 else {
6540 assert(0 && "Unknown instruction!!");
6541 }
6542 }
6543 }
6544 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00006545
6546 if (BinaryOperator::isNot(CondVal)) {
6547 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6548 SI.setOperand(1, FalseVal);
6549 SI.setOperand(2, TrueVal);
6550 return &SI;
6551 }
6552
Chris Lattner3d69f462004-03-12 05:52:32 +00006553 return 0;
6554}
6555
Chris Lattner95a959d2006-03-06 20:18:44 +00006556/// GetKnownAlignment - If the specified pointer has an alignment that we can
6557/// determine, return it, otherwise return 0.
6558static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6559 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6560 unsigned Align = GV->getAlignment();
6561 if (Align == 0 && TD)
6562 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6563 return Align;
6564 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6565 unsigned Align = AI->getAlignment();
6566 if (Align == 0 && TD) {
6567 if (isa<AllocaInst>(AI))
6568 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6569 else if (isa<MallocInst>(AI)) {
6570 // Malloc returns maximally aligned memory.
6571 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6572 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6573 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6574 }
6575 }
6576 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00006577 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00006578 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00006579 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner51c26e92006-03-07 01:28:57 +00006580 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006581 if (isa<PointerType>(CI->getOperand(0)->getType()))
6582 return GetKnownAlignment(CI->getOperand(0), TD);
6583 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00006584 } else if (isa<GetElementPtrInst>(V) ||
6585 (isa<ConstantExpr>(V) &&
6586 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6587 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006588 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6589 if (BaseAlignment == 0) return 0;
6590
6591 // If all indexes are zero, it is just the alignment of the base pointer.
6592 bool AllZeroOperands = true;
6593 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6594 if (!isa<Constant>(GEPI->getOperand(i)) ||
6595 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6596 AllZeroOperands = false;
6597 break;
6598 }
6599 if (AllZeroOperands)
6600 return BaseAlignment;
6601
6602 // Otherwise, if the base alignment is >= the alignment we expect for the
6603 // base pointer type, then we know that the resultant pointer is aligned at
6604 // least as much as its type requires.
6605 if (!TD) return 0;
6606
6607 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6608 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00006609 <= BaseAlignment) {
6610 const Type *GEPTy = GEPI->getType();
6611 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6612 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006613 return 0;
6614 }
6615 return 0;
6616}
6617
Chris Lattner3d69f462004-03-12 05:52:32 +00006618
Chris Lattner8b0ea312006-01-13 20:11:04 +00006619/// visitCallInst - CallInst simplification. This mostly only handles folding
6620/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6621/// the heavy lifting.
6622///
Chris Lattner9fe38862003-06-19 17:00:31 +00006623Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00006624 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6625 if (!II) return visitCallSite(&CI);
6626
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006627 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6628 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00006629 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006630 bool Changed = false;
6631
6632 // memmove/cpy/set of zero bytes is a noop.
6633 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6634 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6635
Chris Lattner35b9e482004-10-12 04:52:52 +00006636 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00006637 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006638 // Replace the instruction with just byte operations. We would
6639 // transform other cases to loads/stores, but we don't know if
6640 // alignment is sufficient.
6641 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006642 }
6643
Chris Lattner35b9e482004-10-12 04:52:52 +00006644 // If we have a memmove and the source operation is a constant global,
6645 // then the source and dest pointers can't alias, so we can change this
6646 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00006647 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006648 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6649 if (GVSrc->isConstant()) {
6650 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00006651 const char *Name;
Andrew Lenharth8ed4c472006-11-03 22:45:50 +00006652 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
Chris Lattner21959392006-03-03 01:34:17 +00006653 Type::UIntTy)
6654 Name = "llvm.memcpy.i32";
6655 else
6656 Name = "llvm.memcpy.i64";
6657 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00006658 CI.getCalledFunction()->getFunctionType());
6659 CI.setOperand(0, MemCpy);
6660 Changed = true;
6661 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006662 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006663
Chris Lattner95a959d2006-03-06 20:18:44 +00006664 // If we can determine a pointer alignment that is bigger than currently
6665 // set, update the alignment.
6666 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6667 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6668 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6669 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00006670 if (MI->getAlignment()->getZExtValue() < Align) {
6671 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00006672 Changed = true;
6673 }
6674 } else if (isa<MemSetInst>(MI)) {
6675 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00006676 if (MI->getAlignment()->getZExtValue() < Alignment) {
6677 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00006678 Changed = true;
6679 }
6680 }
6681
Chris Lattner8b0ea312006-01-13 20:11:04 +00006682 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00006683 } else {
6684 switch (II->getIntrinsicID()) {
6685 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00006686 case Intrinsic::ppc_altivec_lvx:
6687 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00006688 case Intrinsic::x86_sse_loadu_ps:
6689 case Intrinsic::x86_sse2_loadu_pd:
6690 case Intrinsic::x86_sse2_loadu_dq:
6691 // Turn PPC lvx -> load if the pointer is known aligned.
6692 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00006693 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00006694 Value *Ptr = InsertCastBefore(II->getOperand(1),
6695 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00006696 return new LoadInst(Ptr);
6697 }
6698 break;
6699 case Intrinsic::ppc_altivec_stvx:
6700 case Intrinsic::ppc_altivec_stvxl:
6701 // Turn stvx -> store if the pointer is known aligned.
6702 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00006703 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6704 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00006705 return new StoreInst(II->getOperand(1), Ptr);
6706 }
6707 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00006708 case Intrinsic::x86_sse_storeu_ps:
6709 case Intrinsic::x86_sse2_storeu_pd:
6710 case Intrinsic::x86_sse2_storeu_dq:
6711 case Intrinsic::x86_sse2_storel_dq:
6712 // Turn X86 storeu -> store if the pointer is known aligned.
6713 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6714 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6715 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6716 return new StoreInst(II->getOperand(2), Ptr);
6717 }
6718 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00006719
6720 case Intrinsic::x86_sse_cvttss2si: {
6721 // These intrinsics only demands the 0th element of its input vector. If
6722 // we can simplify the input based on that, do so now.
6723 uint64_t UndefElts;
6724 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6725 UndefElts)) {
6726 II->setOperand(1, V);
6727 return II;
6728 }
6729 break;
6730 }
6731
Chris Lattnere2ed0572006-04-06 19:19:17 +00006732 case Intrinsic::ppc_altivec_vperm:
6733 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6734 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6735 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6736
6737 // Check that all of the elements are integer constants or undefs.
6738 bool AllEltsOk = true;
6739 for (unsigned i = 0; i != 16; ++i) {
6740 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6741 !isa<UndefValue>(Mask->getOperand(i))) {
6742 AllEltsOk = false;
6743 break;
6744 }
6745 }
6746
6747 if (AllEltsOk) {
6748 // Cast the input vectors to byte vectors.
6749 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6750 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6751 Value *Result = UndefValue::get(Op0->getType());
6752
6753 // Only extract each element once.
6754 Value *ExtractedElts[32];
6755 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6756
6757 for (unsigned i = 0; i != 16; ++i) {
6758 if (isa<UndefValue>(Mask->getOperand(i)))
6759 continue;
Reid Spencerb83eb642006-10-20 07:07:24 +00006760 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00006761 Idx &= 31; // Match the hardware behavior.
6762
6763 if (ExtractedElts[Idx] == 0) {
6764 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00006765 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006766 InsertNewInstBefore(Elt, CI);
6767 ExtractedElts[Idx] = Elt;
6768 }
6769
6770 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00006771 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006772 InsertNewInstBefore(cast<Instruction>(Result), CI);
6773 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006774 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00006775 }
6776 }
6777 break;
6778
Chris Lattnera728ddc2006-01-13 21:28:09 +00006779 case Intrinsic::stackrestore: {
6780 // If the save is right next to the restore, remove the restore. This can
6781 // happen when variable allocas are DCE'd.
6782 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6783 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6784 BasicBlock::iterator BI = SS;
6785 if (&*++BI == II)
6786 return EraseInstFromFunction(CI);
6787 }
6788 }
6789
6790 // If the stack restore is in a return/unwind block and if there are no
6791 // allocas or calls between the restore and the return, nuke the restore.
6792 TerminatorInst *TI = II->getParent()->getTerminator();
6793 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6794 BasicBlock::iterator BI = II;
6795 bool CannotRemove = false;
6796 for (++BI; &*BI != TI; ++BI) {
6797 if (isa<AllocaInst>(BI) ||
6798 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6799 CannotRemove = true;
6800 break;
6801 }
6802 }
6803 if (!CannotRemove)
6804 return EraseInstFromFunction(CI);
6805 }
6806 break;
6807 }
6808 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006809 }
6810
Chris Lattner8b0ea312006-01-13 20:11:04 +00006811 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006812}
6813
6814// InvokeInst simplification
6815//
6816Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00006817 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006818}
6819
Chris Lattnera44d8a22003-10-07 22:32:43 +00006820// visitCallSite - Improvements for call and invoke instructions.
6821//
6822Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00006823 bool Changed = false;
6824
6825 // If the callee is a constexpr cast of a function, attempt to move the cast
6826 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00006827 if (transformConstExprCastCall(CS)) return 0;
6828
Chris Lattner6c266db2003-10-07 22:54:13 +00006829 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00006830
Chris Lattner08b22ec2005-05-13 07:09:09 +00006831 if (Function *CalleeF = dyn_cast<Function>(Callee))
6832 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6833 Instruction *OldCall = CS.getInstruction();
6834 // If the call and callee calling conventions don't match, this call must
6835 // be unreachable, as the call is undefined.
Chris Lattner47811b72006-09-28 23:35:22 +00006836 new StoreInst(ConstantBool::getTrue(),
Chris Lattner08b22ec2005-05-13 07:09:09 +00006837 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6838 if (!OldCall->use_empty())
6839 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6840 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6841 return EraseInstFromFunction(*OldCall);
6842 return 0;
6843 }
6844
Chris Lattner17be6352004-10-18 02:59:09 +00006845 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6846 // This instruction is not reachable, just remove it. We insert a store to
6847 // undef so that we know that this code is not reachable, despite the fact
6848 // that we can't modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00006849 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00006850 UndefValue::get(PointerType::get(Type::BoolTy)),
6851 CS.getInstruction());
6852
6853 if (!CS.getInstruction()->use_empty())
6854 CS.getInstruction()->
6855 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6856
6857 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6858 // Don't break the CFG, insert a dummy cond branch.
6859 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner47811b72006-09-28 23:35:22 +00006860 ConstantBool::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00006861 }
Chris Lattner17be6352004-10-18 02:59:09 +00006862 return EraseInstFromFunction(*CS.getInstruction());
6863 }
Chris Lattnere87597f2004-10-16 18:11:37 +00006864
Chris Lattner6c266db2003-10-07 22:54:13 +00006865 const PointerType *PTy = cast<PointerType>(Callee->getType());
6866 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6867 if (FTy->isVarArg()) {
6868 // See if we can optimize any arguments passed through the varargs area of
6869 // the call.
6870 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6871 E = CS.arg_end(); I != E; ++I)
6872 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6873 // If this cast does not effect the value passed through the varargs
6874 // area, we can eliminate the use of the cast.
6875 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00006876 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00006877 *I = Op;
6878 Changed = true;
6879 }
6880 }
6881 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006882
Chris Lattner6c266db2003-10-07 22:54:13 +00006883 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00006884}
6885
Chris Lattner9fe38862003-06-19 17:00:31 +00006886// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6887// attempt to move the cast to the arguments of the call/invoke.
6888//
6889bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6890 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6891 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00006892 if (CE->getOpcode() != Instruction::BitCast ||
6893 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00006894 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00006895 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00006896 Instruction *Caller = CS.getInstruction();
6897
6898 // Okay, this is a cast from a function to a different type. Unless doing so
6899 // would cause a type conversion of one of our arguments, change this call to
6900 // be a direct call with arguments casted to the appropriate types.
6901 //
6902 const FunctionType *FT = Callee->getFunctionType();
6903 const Type *OldRetTy = Caller->getType();
6904
Chris Lattnerf78616b2004-01-14 06:06:08 +00006905 // Check to see if we are changing the return type...
6906 if (OldRetTy != FT->getReturnType()) {
6907 if (Callee->isExternal() &&
Reid Spencer3da59db2006-11-27 01:05:10 +00006908 !Caller->use_empty() &&
6909 !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00006910 (isa<PointerType>(FT->getReturnType()) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00006911 TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6912 )
Chris Lattnerf78616b2004-01-14 06:06:08 +00006913 return false; // Cannot transform this return value...
6914
6915 // If the callsite is an invoke instruction, and the return value is used by
6916 // a PHI node in a successor, we cannot change the return type of the call
6917 // because there is no place to put the cast instruction (without breaking
6918 // the critical edge). Bail out in this case.
6919 if (!Caller->use_empty())
6920 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6921 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6922 UI != E; ++UI)
6923 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6924 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006925 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00006926 return false;
6927 }
Chris Lattner9fe38862003-06-19 17:00:31 +00006928
6929 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6930 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006931
Chris Lattner9fe38862003-06-19 17:00:31 +00006932 CallSite::arg_iterator AI = CS.arg_begin();
6933 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6934 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006935 const Type *ActTy = (*AI)->getType();
Reid Spencer3da59db2006-11-27 01:05:10 +00006936 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006937 //Either we can cast directly, or we can upconvert the argument
Reid Spencer3da59db2006-11-27 01:05:10 +00006938 bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006939 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6940 ParamTy->isSigned() == ActTy->isSigned() &&
6941 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6942 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencerb83eb642006-10-20 07:07:24 +00006943 c->getSExtValue() > 0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006944 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00006945 }
6946
6947 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6948 Callee->isExternal())
6949 return false; // Do not delete arguments unless we have a function body...
6950
6951 // Okay, we decided that this is a safe thing to do: go ahead and start
6952 // inserting cast instructions as necessary...
6953 std::vector<Value*> Args;
6954 Args.reserve(NumActualArgs);
6955
6956 AI = CS.arg_begin();
6957 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6958 const Type *ParamTy = FT->getParamType(i);
6959 if ((*AI)->getType() == ParamTy) {
6960 Args.push_back(*AI);
6961 } else {
Reid Spencer3da59db2006-11-27 01:05:10 +00006962 CastInst *NewCast = CastInst::createInferredCast(*AI, ParamTy, "tmp");
6963 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00006964 }
6965 }
6966
6967 // If the function takes more arguments than the call was taking, add them
6968 // now...
6969 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6970 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6971
6972 // If we are removing arguments to the function, emit an obnoxious warning...
6973 if (FT->getNumParams() < NumActualArgs)
6974 if (!FT->isVarArg()) {
Bill Wendlingb7427032006-11-26 09:46:52 +00006975 llvm_cerr << "WARNING: While resolving call to function '"
Chris Lattner9fe38862003-06-19 17:00:31 +00006976 << Callee->getName() << "' arguments were dropped!\n";
6977 } else {
6978 // Add all of the arguments in their promoted form to the arg list...
6979 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6980 const Type *PTy = getPromotedType((*AI)->getType());
6981 if (PTy != (*AI)->getType()) {
6982 // Must promote to pass through va_arg area!
Reid Spencer3da59db2006-11-27 01:05:10 +00006983 Instruction *Cast = CastInst::createInferredCast(*AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00006984 InsertNewInstBefore(Cast, *Caller);
6985 Args.push_back(Cast);
6986 } else {
6987 Args.push_back(*AI);
6988 }
6989 }
6990 }
6991
6992 if (FT->getReturnType() == Type::VoidTy)
6993 Caller->setName(""); // Void type should not have a name...
6994
6995 Instruction *NC;
6996 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006997 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00006998 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00006999 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007000 } else {
7001 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00007002 if (cast<CallInst>(Caller)->isTailCall())
7003 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00007004 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00007005 }
7006
7007 // Insert a cast of the return type as necessary...
7008 Value *NV = NC;
7009 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7010 if (NV->getType() != Type::VoidTy) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007011 NV = NC = CastInst::createInferredCast(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00007012
7013 // If this is an invoke instruction, we should insert it after the first
7014 // non-phi, instruction in the normal successor block.
7015 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7016 BasicBlock::iterator I = II->getNormalDest()->begin();
7017 while (isa<PHINode>(I)) ++I;
7018 InsertNewInstBefore(NC, *I);
7019 } else {
7020 // Otherwise, it's a call, just insert cast right after the call instr
7021 InsertNewInstBefore(NC, *Caller);
7022 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007023 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00007024 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00007025 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00007026 }
7027 }
7028
7029 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7030 Caller->replaceAllUsesWith(NV);
7031 Caller->getParent()->getInstList().erase(Caller);
7032 removeFromWorkList(Caller);
7033 return true;
7034}
7035
Chris Lattner7da52b22006-11-01 04:51:18 +00007036/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7037/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7038/// and a single binop.
7039Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7040 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007041 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7042 isa<GetElementPtrInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00007043 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007044 Value *LHSVal = FirstInst->getOperand(0);
7045 Value *RHSVal = FirstInst->getOperand(1);
7046
7047 const Type *LHSType = LHSVal->getType();
7048 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00007049
7050 // Scan to see if all operands are the same opcode, all have one use, and all
7051 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00007052 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00007053 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00007054 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7055 // Verify type of the LHS matches so we don't fold setcc's of different
Chris Lattner9c080502006-11-01 07:43:41 +00007056 // types or GEP's with different index types.
7057 I->getOperand(0)->getType() != LHSType ||
7058 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00007059 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007060
7061 // Keep track of which operand needs a phi node.
7062 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7063 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00007064 }
7065
Chris Lattner53738a42006-11-08 19:42:28 +00007066 // Otherwise, this is safe to transform, determine if it is profitable.
7067
7068 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7069 // Indexes are often folded into load/store instructions, so we don't want to
7070 // hide them behind a phi.
7071 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7072 return 0;
7073
Chris Lattner7da52b22006-11-01 04:51:18 +00007074 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00007075 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00007076 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007077 if (LHSVal == 0) {
7078 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7079 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7080 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007081 InsertNewInstBefore(NewLHS, PN);
7082 LHSVal = NewLHS;
7083 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007084
7085 if (RHSVal == 0) {
7086 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7087 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7088 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00007089 InsertNewInstBefore(NewRHS, PN);
7090 RHSVal = NewRHS;
7091 }
7092
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00007093 // Add all operands to the new PHIs.
7094 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7095 if (NewLHS) {
7096 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7097 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7098 }
7099 if (NewRHS) {
7100 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7101 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7102 }
7103 }
7104
Chris Lattner7da52b22006-11-01 04:51:18 +00007105 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00007106 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7107 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7108 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7109 else {
7110 assert(isa<GetElementPtrInst>(FirstInst));
7111 return new GetElementPtrInst(LHSVal, RHSVal);
7112 }
Chris Lattner7da52b22006-11-01 04:51:18 +00007113}
7114
Chris Lattner76c73142006-11-01 07:13:54 +00007115/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7116/// of the block that defines it. This means that it must be obvious the value
7117/// of the load is not changed from the point of the load to the end of the
7118/// block it is in.
7119static bool isSafeToSinkLoad(LoadInst *L) {
7120 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7121
7122 for (++BBI; BBI != E; ++BBI)
7123 if (BBI->mayWriteToMemory())
7124 return false;
7125 return true;
7126}
7127
Chris Lattner9fe38862003-06-19 17:00:31 +00007128
Chris Lattnerbac32862004-11-14 19:13:23 +00007129// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7130// operator and they all are only used by the PHI, PHI together their
7131// inputs, and do the operation once, to the result of the PHI.
7132Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7133 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7134
7135 // Scan the instruction, looking for input operations that can be folded away.
7136 // If all input operands to the phi are the same instruction (e.g. a cast from
7137 // the same type or "+42") we can pull the operation through the PHI, reducing
7138 // code size and simplifying code.
7139 Constant *ConstantOp = 0;
7140 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00007141 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00007142 if (isa<CastInst>(FirstInst)) {
7143 CastSrcTy = FirstInst->getOperand(0)->getType();
7144 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
Chris Lattner7da52b22006-11-01 04:51:18 +00007145 // Can fold binop or shift here if the RHS is a constant, otherwise call
7146 // FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00007147 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00007148 if (ConstantOp == 0)
7149 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00007150 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7151 isVolatile = LI->isVolatile();
7152 // We can't sink the load if the loaded value could be modified between the
7153 // load and the PHI.
7154 if (LI->getParent() != PN.getIncomingBlock(0) ||
7155 !isSafeToSinkLoad(LI))
7156 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00007157 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00007158 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00007159 return FoldPHIArgBinOpIntoPHI(PN);
7160 // Can't handle general GEPs yet.
7161 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007162 } else {
7163 return 0; // Cannot fold this operation.
7164 }
7165
7166 // Check to see if all arguments are the same operation.
7167 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7168 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7169 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7170 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7171 return 0;
7172 if (CastSrcTy) {
7173 if (I->getOperand(0)->getType() != CastSrcTy)
7174 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00007175 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7176 // We can't sink the load if the loaded value could be modified between the
7177 // load and the PHI.
7178 if (LI->isVolatile() != isVolatile ||
7179 LI->getParent() != PN.getIncomingBlock(i) ||
7180 !isSafeToSinkLoad(LI))
7181 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00007182 } else if (I->getOperand(1) != ConstantOp) {
7183 return 0;
7184 }
7185 }
7186
7187 // Okay, they are all the same operation. Create a new PHI node of the
7188 // correct type, and PHI together all of the LHS's of the instructions.
7189 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7190 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00007191 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00007192
7193 Value *InVal = FirstInst->getOperand(0);
7194 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00007195
7196 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00007197 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7198 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7199 if (NewInVal != InVal)
7200 InVal = 0;
7201 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7202 }
7203
7204 Value *PhiVal;
7205 if (InVal) {
7206 // The new PHI unions all of the same values together. This is really
7207 // common, so we handle it intelligently here for compile-time speed.
7208 PhiVal = InVal;
7209 delete NewPN;
7210 } else {
7211 InsertNewInstBefore(NewPN, PN);
7212 PhiVal = NewPN;
7213 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007214
Chris Lattnerbac32862004-11-14 19:13:23 +00007215 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00007216 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7217 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00007218 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00007219 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00007220 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00007221 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00007222 else
7223 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00007224 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00007225}
Chris Lattnera1be5662002-05-02 17:06:02 +00007226
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007227/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7228/// that is dead.
7229static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7230 if (PN->use_empty()) return true;
7231 if (!PN->hasOneUse()) return false;
7232
7233 // Remember this node, and if we find the cycle, return.
7234 if (!PotentiallyDeadPHIs.insert(PN).second)
7235 return true;
7236
7237 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7238 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00007239
Chris Lattnera3fd1c52005-01-17 05:10:15 +00007240 return false;
7241}
7242
Chris Lattner473945d2002-05-06 18:06:38 +00007243// PHINode simplification
7244//
Chris Lattner7e708292002-06-25 16:13:24 +00007245Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00007246 // If LCSSA is around, don't mess with Phi nodes
7247 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00007248
Owen Anderson7e057142006-07-10 22:03:18 +00007249 if (Value *V = PN.hasConstantValue())
7250 return ReplaceInstUsesWith(PN, V);
7251
Owen Anderson7e057142006-07-10 22:03:18 +00007252 // If all PHI operands are the same operation, pull them through the PHI,
7253 // reducing code size.
7254 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7255 PN.getIncomingValue(0)->hasOneUse())
7256 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7257 return Result;
7258
7259 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7260 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7261 // PHI)... break the cycle.
7262 if (PN.hasOneUse())
7263 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7264 std::set<PHINode*> PotentiallyDeadPHIs;
7265 PotentiallyDeadPHIs.insert(&PN);
7266 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7267 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7268 }
7269
Chris Lattner60921c92003-12-19 05:58:40 +00007270 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00007271}
7272
Chris Lattner28977af2004-04-05 01:30:19 +00007273static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7274 Instruction *InsertPoint,
7275 InstCombiner *IC) {
7276 unsigned PS = IC->getTargetData().getPointerSize();
7277 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00007278 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7279 // We must insert a cast to ensure we sign-extend.
Reid Spencer811b0cb2006-10-26 19:19:06 +00007280 V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7281 return IC->InsertCastBefore(V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00007282}
7283
Chris Lattnera1be5662002-05-02 17:06:02 +00007284
Chris Lattner7e708292002-06-25 16:13:24 +00007285Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00007286 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00007287 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00007288 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007289 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00007290 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007291
Chris Lattnere87597f2004-10-16 18:11:37 +00007292 if (isa<UndefValue>(GEP.getOperand(0)))
7293 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7294
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007295 bool HasZeroPointerIndex = false;
7296 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7297 HasZeroPointerIndex = C->isNullValue();
7298
7299 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00007300 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00007301
Chris Lattner28977af2004-04-05 01:30:19 +00007302 // Eliminate unneeded casts for indices.
7303 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007304 gep_type_iterator GTI = gep_type_begin(GEP);
7305 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7306 if (isa<SequentialType>(*GTI)) {
7307 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7308 Value *Src = CI->getOperand(0);
7309 const Type *SrcTy = Src->getType();
7310 const Type *DestTy = CI->getType();
7311 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007312 if (SrcTy->getPrimitiveSizeInBits() ==
7313 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007314 // We can always eliminate a cast from ulong or long to the other.
7315 // We can always eliminate a cast from uint to int or the other on
7316 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00007317 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007318 MadeChange = true;
7319 GEP.setOperand(i, Src);
7320 }
7321 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7322 SrcTy->getPrimitiveSize() == 4) {
7323 // We can always eliminate a cast from int to [u]long. We can
7324 // eliminate a cast from uint to [u]long iff the target is a 32-bit
7325 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00007326 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00007327 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007328 MadeChange = true;
7329 GEP.setOperand(i, Src);
7330 }
Chris Lattner28977af2004-04-05 01:30:19 +00007331 }
7332 }
7333 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007334 // If we are using a wider index than needed for this platform, shrink it
7335 // to what we need. If the incoming value needs a cast instruction,
7336 // insert it. This explicit cast can make subsequent optimizations more
7337 // obvious.
7338 Value *Op = GEP.getOperand(i);
7339 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00007340 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00007341 GEP.setOperand(i, ConstantExpr::getCast(C,
7342 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00007343 MadeChange = true;
7344 } else {
Reid Spencer811b0cb2006-10-26 19:19:06 +00007345 Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00007346 GEP.setOperand(i, Op);
7347 MadeChange = true;
7348 }
Chris Lattner67769e52004-07-20 01:48:15 +00007349
7350 // If this is a constant idx, make sure to canonicalize it to be a signed
7351 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencerb83eb642006-10-20 07:07:24 +00007352 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7353 if (CUI->getType()->isUnsigned()) {
7354 GEP.setOperand(i,
7355 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7356 MadeChange = true;
7357 }
Chris Lattner28977af2004-04-05 01:30:19 +00007358 }
7359 if (MadeChange) return &GEP;
7360
Chris Lattner90ac28c2002-08-02 19:29:35 +00007361 // Combine Indices - If the source pointer to this getelementptr instruction
7362 // is a getelementptr instruction, combine the indices of the two
7363 // getelementptr instructions into a single instruction.
7364 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00007365 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00007366 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00007367 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00007368
7369 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00007370 // Note that if our source is a gep chain itself that we wait for that
7371 // chain to be resolved before we perform this transformation. This
7372 // avoids us creating a TON of code in some cases.
7373 //
7374 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7375 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7376 return 0; // Wait until our source is folded to completion.
7377
Chris Lattner90ac28c2002-08-02 19:29:35 +00007378 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00007379
7380 // Find out whether the last index in the source GEP is a sequential idx.
7381 bool EndsWithSequential = false;
7382 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7383 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00007384 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00007385
Chris Lattner90ac28c2002-08-02 19:29:35 +00007386 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00007387 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00007388 // Replace: gep (gep %P, long B), long A, ...
7389 // With: T = long A+B; gep %P, T, ...
7390 //
Chris Lattner620ce142004-05-07 22:09:22 +00007391 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00007392 if (SO1 == Constant::getNullValue(SO1->getType())) {
7393 Sum = GO1;
7394 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7395 Sum = SO1;
7396 } else {
7397 // If they aren't the same type, convert both to an integer of the
7398 // target's pointer size.
7399 if (SO1->getType() != GO1->getType()) {
7400 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7401 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7402 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7403 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7404 } else {
7405 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00007406 if (SO1->getType()->getPrimitiveSize() == PS) {
7407 // Convert GO1 to SO1's type.
7408 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7409
7410 } else if (GO1->getType()->getPrimitiveSize() == PS) {
7411 // Convert SO1 to GO1's type.
7412 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7413 } else {
7414 const Type *PT = TD->getIntPtrType();
7415 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7416 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7417 }
7418 }
7419 }
Chris Lattner620ce142004-05-07 22:09:22 +00007420 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7421 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7422 else {
Chris Lattner48595f12004-06-10 02:07:29 +00007423 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7424 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00007425 }
Chris Lattner28977af2004-04-05 01:30:19 +00007426 }
Chris Lattner620ce142004-05-07 22:09:22 +00007427
7428 // Recycle the GEP we already have if possible.
7429 if (SrcGEPOperands.size() == 2) {
7430 GEP.setOperand(0, SrcGEPOperands[0]);
7431 GEP.setOperand(1, Sum);
7432 return &GEP;
7433 } else {
7434 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7435 SrcGEPOperands.end()-1);
7436 Indices.push_back(Sum);
7437 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7438 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007439 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00007440 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007441 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00007442 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00007443 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7444 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00007445 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7446 }
7447
7448 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00007449 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00007450
Chris Lattner620ce142004-05-07 22:09:22 +00007451 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00007452 // GEP of global variable. If all of the indices for this GEP are
7453 // constants, we can promote this to a constexpr instead of an instruction.
7454
7455 // Scan for nonconstants...
7456 std::vector<Constant*> Indices;
7457 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7458 for (; I != E && isa<Constant>(*I); ++I)
7459 Indices.push_back(cast<Constant>(*I));
7460
7461 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00007462 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00007463
7464 // Replace all uses of the GEP with the new constexpr...
7465 return ReplaceInstUsesWith(GEP, CE);
7466 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007467 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00007468 if (!isa<PointerType>(X->getType())) {
7469 // Not interesting. Source pointer must be a cast from pointer.
7470 } else if (HasZeroPointerIndex) {
7471 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7472 // into : GEP [10 x ubyte]* X, long 0, ...
7473 //
7474 // This occurs when the program declares an array extern like "int X[];"
7475 //
7476 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7477 const PointerType *XTy = cast<PointerType>(X->getType());
7478 if (const ArrayType *XATy =
7479 dyn_cast<ArrayType>(XTy->getElementType()))
7480 if (const ArrayType *CATy =
7481 dyn_cast<ArrayType>(CPTy->getElementType()))
7482 if (CATy->getElementType() == XATy->getElementType()) {
7483 // At this point, we know that the cast source type is a pointer
7484 // to an array of the same type as the destination pointer
7485 // array. Because the array type is never stepped over (there
7486 // is a leading zero) we can fold the cast into this GEP.
7487 GEP.setOperand(0, X);
7488 return &GEP;
7489 }
7490 } else if (GEP.getNumOperands() == 2) {
7491 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00007492 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7493 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00007494 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7495 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7496 if (isa<ArrayType>(SrcElTy) &&
7497 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7498 TD->getTypeSize(ResElTy)) {
7499 Value *V = InsertNewInstBefore(
7500 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7501 GEP.getOperand(1), GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00007502 // V and GEP are both pointer types --> BitCast
7503 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007504 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00007505
7506 // Transform things like:
7507 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7508 // (where tmp = 8*tmp2) into:
7509 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7510
7511 if (isa<ArrayType>(SrcElTy) &&
7512 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7513 uint64_t ArrayEltSize =
7514 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7515
7516 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7517 // allow either a mul, shift, or constant here.
7518 Value *NewIdx = 0;
7519 ConstantInt *Scale = 0;
7520 if (ArrayEltSize == 1) {
7521 NewIdx = GEP.getOperand(1);
7522 Scale = ConstantInt::get(NewIdx->getType(), 1);
7523 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00007524 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007525 Scale = CI;
7526 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7527 if (Inst->getOpcode() == Instruction::Shl &&
7528 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007529 unsigned ShAmt =
7530 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner7835cdd2005-09-13 18:36:04 +00007531 if (Inst->getType()->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +00007532 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007533 else
Reid Spencerb83eb642006-10-20 07:07:24 +00007534 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007535 NewIdx = Inst->getOperand(0);
7536 } else if (Inst->getOpcode() == Instruction::Mul &&
7537 isa<ConstantInt>(Inst->getOperand(1))) {
7538 Scale = cast<ConstantInt>(Inst->getOperand(1));
7539 NewIdx = Inst->getOperand(0);
7540 }
7541 }
7542
7543 // If the index will be to exactly the right offset with the scale taken
7544 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00007545 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
Reid Spencer3ed469c2006-11-02 20:25:50 +00007546 if (isa<ConstantInt>(Scale))
Reid Spencerb83eb642006-10-20 07:07:24 +00007547 Scale = ConstantInt::get(Scale->getType(),
7548 Scale->getZExtValue() / ArrayEltSize);
7549 if (Scale->getZExtValue() != 1) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00007550 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7551 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7552 NewIdx = InsertNewInstBefore(Sc, GEP);
7553 }
7554
7555 // Insert the new GEP instruction.
Reid Spencer3da59db2006-11-27 01:05:10 +00007556 Instruction *NewGEP =
Chris Lattner7835cdd2005-09-13 18:36:04 +00007557 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7558 NewIdx, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00007559 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7560 // The NewGEP must be pointer typed, so must the old one -> BitCast
7561 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00007562 }
7563 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007564 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007565 }
7566
Chris Lattner8a2a3112001-12-14 16:52:21 +00007567 return 0;
7568}
7569
Chris Lattner0864acf2002-11-04 16:18:53 +00007570Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7571 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7572 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00007573 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7574 const Type *NewTy =
7575 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00007576 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00007577
7578 // Create and insert the replacement instruction...
7579 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00007580 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007581 else {
7582 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00007583 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007584 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007585
7586 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007587
Chris Lattner0864acf2002-11-04 16:18:53 +00007588 // Scan to the end of the allocation instructions, to skip over a block of
7589 // allocas if possible...
7590 //
7591 BasicBlock::iterator It = New;
7592 while (isa<AllocationInst>(*It)) ++It;
7593
7594 // Now that I is pointing to the first non-allocation-inst in the block,
7595 // insert our getelementptr instruction...
7596 //
Chris Lattner693787a2005-05-04 19:10:26 +00007597 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7598 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7599 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00007600
7601 // Now make everything use the getelementptr instead of the original
7602 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00007603 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00007604 } else if (isa<UndefValue>(AI.getArraySize())) {
7605 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00007606 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007607
7608 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7609 // Note that we only do this for alloca's, because malloc should allocate and
7610 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00007611 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00007612 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00007613 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7614
Chris Lattner0864acf2002-11-04 16:18:53 +00007615 return 0;
7616}
7617
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007618Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7619 Value *Op = FI.getOperand(0);
7620
7621 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7622 if (CastInst *CI = dyn_cast<CastInst>(Op))
7623 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7624 FI.setOperand(0, CI->getOperand(0));
7625 return &FI;
7626 }
7627
Chris Lattner17be6352004-10-18 02:59:09 +00007628 // free undef -> unreachable.
7629 if (isa<UndefValue>(Op)) {
7630 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00007631 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00007632 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7633 return EraseInstFromFunction(FI);
7634 }
7635
Chris Lattner6160e852004-02-28 04:57:37 +00007636 // If we have 'free null' delete the instruction. This can happen in stl code
7637 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00007638 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007639 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00007640
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007641 return 0;
7642}
7643
7644
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007645/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00007646static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7647 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00007648 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00007649
7650 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007651 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00007652 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007653
Chris Lattnera1c35382006-04-02 05:37:12 +00007654 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7655 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00007656 // If the source is an array, the code below will not succeed. Check to
7657 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7658 // constants.
7659 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7660 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7661 if (ASrcTy->getNumElements() != 0) {
7662 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7663 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7664 SrcTy = cast<PointerType>(CastOp->getType());
7665 SrcPTy = SrcTy->getElementType();
7666 }
7667
Chris Lattnera1c35382006-04-02 05:37:12 +00007668 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7669 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00007670 // Do not allow turning this into a load of an integer, which is then
7671 // casted to a pointer, this pessimizes pointer analysis a lot.
7672 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007673 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00007674 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00007675
Chris Lattnerf9527852005-01-31 04:50:46 +00007676 // Okay, we are casting from one integer or pointer type to another of
7677 // the same size. Instead of casting the pointer before the load, cast
7678 // the result of the loaded value.
7679 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7680 CI->getName(),
7681 LI.isVolatile()),LI);
7682 // Now cast the result of the load.
Reid Spencer3da59db2006-11-27 01:05:10 +00007683 return CastInst::createInferredCast(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00007684 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00007685 }
7686 }
7687 return 0;
7688}
7689
Chris Lattnerc10aced2004-09-19 18:43:46 +00007690/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00007691/// from this value cannot trap. If it is not obviously safe to load from the
7692/// specified pointer, we do a quick local scan of the basic block containing
7693/// ScanFrom, to determine if the address is already accessed.
7694static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7695 // If it is an alloca or global variable, it is always safe to load from.
7696 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7697
7698 // Otherwise, be a little bit agressive by scanning the local block where we
7699 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007700 // from/to. If so, the previous load or store would have already trapped,
7701 // so there is no harm doing an extra load (also, CSE will later eliminate
7702 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00007703 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7704
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007705 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00007706 --BBI;
7707
7708 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7709 if (LI->getOperand(0) == V) return true;
7710 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7711 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00007712
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007713 }
Chris Lattner8a375202004-09-19 19:18:10 +00007714 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00007715}
7716
Chris Lattner833b8a42003-06-26 05:06:25 +00007717Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7718 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00007719
Chris Lattner37366c12005-05-01 04:24:53 +00007720 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00007721 if (isa<CastInst>(Op))
Chris Lattner37366c12005-05-01 04:24:53 +00007722 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7723 return Res;
7724
7725 // None of the following transforms are legal for volatile loads.
7726 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00007727
Chris Lattner62f254d2005-09-12 22:00:15 +00007728 if (&LI.getParent()->front() != &LI) {
7729 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00007730 // If the instruction immediately before this is a store to the same
7731 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00007732 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7733 if (SI->getOperand(1) == LI.getOperand(0))
7734 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00007735 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7736 if (LIB->getOperand(0) == LI.getOperand(0))
7737 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00007738 }
Chris Lattner37366c12005-05-01 04:24:53 +00007739
7740 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7741 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7742 isa<UndefValue>(GEPI->getOperand(0))) {
7743 // Insert a new store to null instruction before the load to indicate
7744 // that this code is not reachable. We do this instead of inserting
7745 // an unreachable instruction directly because we cannot modify the
7746 // CFG.
7747 new StoreInst(UndefValue::get(LI.getType()),
7748 Constant::getNullValue(Op->getType()), &LI);
7749 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7750 }
7751
Chris Lattnere87597f2004-10-16 18:11:37 +00007752 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00007753 // load null/undef -> undef
7754 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00007755 // Insert a new store to null instruction before the load to indicate that
7756 // this code is not reachable. We do this instead of inserting an
7757 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00007758 new StoreInst(UndefValue::get(LI.getType()),
7759 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00007760 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00007761 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007762
Chris Lattnere87597f2004-10-16 18:11:37 +00007763 // Instcombine load (constant global) into the value loaded.
7764 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7765 if (GV->isConstant() && !GV->isExternal())
7766 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00007767
Chris Lattnere87597f2004-10-16 18:11:37 +00007768 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7769 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7770 if (CE->getOpcode() == Instruction::GetElementPtr) {
7771 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7772 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00007773 if (Constant *V =
7774 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00007775 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00007776 if (CE->getOperand(0)->isNullValue()) {
7777 // Insert a new store to null instruction before the load to indicate
7778 // that this code is not reachable. We do this instead of inserting
7779 // an unreachable instruction directly because we cannot modify the
7780 // CFG.
7781 new StoreInst(UndefValue::get(LI.getType()),
7782 Constant::getNullValue(Op->getType()), &LI);
7783 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7784 }
7785
Reid Spencer3da59db2006-11-27 01:05:10 +00007786 } else if (CE->isCast()) {
Chris Lattnere87597f2004-10-16 18:11:37 +00007787 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7788 return Res;
7789 }
7790 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00007791
Chris Lattner37366c12005-05-01 04:24:53 +00007792 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00007793 // Change select and PHI nodes to select values instead of addresses: this
7794 // helps alias analysis out a lot, allows many others simplifications, and
7795 // exposes redundancy in the code.
7796 //
7797 // Note that we cannot do the transformation unless we know that the
7798 // introduced loads cannot trap! Something like this is valid as long as
7799 // the condition is always false: load (select bool %C, int* null, int* %G),
7800 // but it would not be valid if we transformed it to load from null
7801 // unconditionally.
7802 //
7803 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7804 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00007805 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7806 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00007807 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007808 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00007809 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007810 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00007811 return new SelectInst(SI->getCondition(), V1, V2);
7812 }
7813
Chris Lattner684fe212004-09-23 15:46:00 +00007814 // load (select (cond, null, P)) -> load P
7815 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7816 if (C->isNullValue()) {
7817 LI.setOperand(0, SI->getOperand(2));
7818 return &LI;
7819 }
7820
7821 // load (select (cond, P, null)) -> load P
7822 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7823 if (C->isNullValue()) {
7824 LI.setOperand(0, SI->getOperand(1));
7825 return &LI;
7826 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00007827 }
7828 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007829 return 0;
7830}
7831
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007832/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7833/// when possible.
7834static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7835 User *CI = cast<User>(SI.getOperand(1));
7836 Value *CastOp = CI->getOperand(0);
7837
7838 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7839 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7840 const Type *SrcPTy = SrcTy->getElementType();
7841
7842 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7843 // If the source is an array, the code below will not succeed. Check to
7844 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7845 // constants.
7846 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7847 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7848 if (ASrcTy->getNumElements() != 0) {
7849 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7850 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7851 SrcTy = cast<PointerType>(CastOp->getType());
7852 SrcPTy = SrcTy->getElementType();
7853 }
7854
7855 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007856 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007857 IC.getTargetData().getTypeSize(DestPTy)) {
7858
7859 // Okay, we are casting from one integer or pointer type to another of
7860 // the same size. Instead of casting the pointer before the store, cast
7861 // the value to be stored.
7862 Value *NewCast;
7863 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7864 NewCast = ConstantExpr::getCast(C, SrcPTy);
7865 else
Reid Spencer3da59db2006-11-27 01:05:10 +00007866 NewCast = IC.InsertNewInstBefore(
7867 CastInst::createInferredCast(SI.getOperand(0), SrcPTy,
7868 SI.getOperand(0)->getName()+".c"), SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007869
7870 return new StoreInst(NewCast, CastOp);
7871 }
7872 }
7873 }
7874 return 0;
7875}
7876
Chris Lattner2f503e62005-01-31 05:36:43 +00007877Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7878 Value *Val = SI.getOperand(0);
7879 Value *Ptr = SI.getOperand(1);
7880
7881 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00007882 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007883 ++NumCombined;
7884 return 0;
7885 }
7886
Chris Lattner9ca96412006-02-08 03:25:32 +00007887 // Do really simple DSE, to catch cases where there are several consequtive
7888 // stores to the same location, separated by a few arithmetic operations. This
7889 // situation often occurs with bitfield accesses.
7890 BasicBlock::iterator BBI = &SI;
7891 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7892 --ScanInsts) {
7893 --BBI;
7894
7895 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7896 // Prev store isn't volatile, and stores to the same location?
7897 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7898 ++NumDeadStore;
7899 ++BBI;
7900 EraseInstFromFunction(*PrevSI);
7901 continue;
7902 }
7903 break;
7904 }
7905
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007906 // If this is a load, we have to stop. However, if the loaded value is from
7907 // the pointer we're loading and is producing the pointer we're storing,
7908 // then *this* store is dead (X = load P; store X -> P).
7909 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7910 if (LI == Val && LI->getOperand(0) == Ptr) {
7911 EraseInstFromFunction(SI);
7912 ++NumCombined;
7913 return 0;
7914 }
7915 // Otherwise, this is a load from some other location. Stores before it
7916 // may not be dead.
7917 break;
7918 }
7919
Chris Lattner9ca96412006-02-08 03:25:32 +00007920 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007921 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00007922 break;
7923 }
7924
7925
7926 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00007927
7928 // store X, null -> turns into 'unreachable' in SimplifyCFG
7929 if (isa<ConstantPointerNull>(Ptr)) {
7930 if (!isa<UndefValue>(Val)) {
7931 SI.setOperand(0, UndefValue::get(Val->getType()));
7932 if (Instruction *U = dyn_cast<Instruction>(Val))
7933 WorkList.push_back(U); // Dropped a use.
7934 ++NumCombined;
7935 }
7936 return 0; // Do not modify these!
7937 }
7938
7939 // store undef, Ptr -> noop
7940 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00007941 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007942 ++NumCombined;
7943 return 0;
7944 }
7945
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007946 // If the pointer destination is a cast, see if we can fold the cast into the
7947 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00007948 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007949 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7950 return Res;
7951 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00007952 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007953 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7954 return Res;
7955
Chris Lattner408902b2005-09-12 23:23:25 +00007956
7957 // If this store is the last instruction in the basic block, and if the block
7958 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00007959 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00007960 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7961 if (BI->isUnconditional()) {
7962 // Check to see if the successor block has exactly two incoming edges. If
7963 // so, see if the other predecessor contains a store to the same location.
7964 // if so, insert a PHI node (if needed) and move the stores down.
7965 BasicBlock *Dest = BI->getSuccessor(0);
7966
7967 pred_iterator PI = pred_begin(Dest);
7968 BasicBlock *Other = 0;
7969 if (*PI != BI->getParent())
7970 Other = *PI;
7971 ++PI;
7972 if (PI != pred_end(Dest)) {
7973 if (*PI != BI->getParent())
7974 if (Other)
7975 Other = 0;
7976 else
7977 Other = *PI;
7978 if (++PI != pred_end(Dest))
7979 Other = 0;
7980 }
7981 if (Other) { // If only one other pred...
7982 BBI = Other->getTerminator();
7983 // Make sure this other block ends in an unconditional branch and that
7984 // there is an instruction before the branch.
7985 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7986 BBI != Other->begin()) {
7987 --BBI;
7988 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7989
7990 // If this instruction is a store to the same location.
7991 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7992 // Okay, we know we can perform this transformation. Insert a PHI
7993 // node now if we need it.
7994 Value *MergedVal = OtherStore->getOperand(0);
7995 if (MergedVal != SI.getOperand(0)) {
7996 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7997 PN->reserveOperandSpace(2);
7998 PN->addIncoming(SI.getOperand(0), SI.getParent());
7999 PN->addIncoming(OtherStore->getOperand(0), Other);
8000 MergedVal = InsertNewInstBefore(PN, Dest->front());
8001 }
8002
8003 // Advance to a place where it is safe to insert the new store and
8004 // insert it.
8005 BBI = Dest->begin();
8006 while (isa<PHINode>(BBI)) ++BBI;
8007 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8008 OtherStore->isVolatile()), *BBI);
8009
8010 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00008011 EraseInstFromFunction(SI);
8012 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00008013 ++NumCombined;
8014 return 0;
8015 }
8016 }
8017 }
8018 }
8019
Chris Lattner2f503e62005-01-31 05:36:43 +00008020 return 0;
8021}
8022
8023
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008024Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8025 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00008026 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008027 BasicBlock *TrueDest;
8028 BasicBlock *FalseDest;
8029 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8030 !isa<Constant>(X)) {
8031 // Swap Destinations and condition...
8032 BI.setCondition(X);
8033 BI.setSuccessor(0, FalseDest);
8034 BI.setSuccessor(1, TrueDest);
8035 return &BI;
8036 }
8037
8038 // Cannonicalize setne -> seteq
8039 Instruction::BinaryOps Op; Value *Y;
8040 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8041 TrueDest, FalseDest)))
8042 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8043 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8044 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8045 std::string Name = I->getName(); I->setName("");
8046 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8047 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00008048 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008049 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00008050 BI.setSuccessor(0, FalseDest);
8051 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00008052 removeFromWorkList(I);
8053 I->getParent()->getInstList().erase(I);
8054 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00008055 return &BI;
8056 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008057
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00008058 return 0;
8059}
Chris Lattner0864acf2002-11-04 16:18:53 +00008060
Chris Lattner46238a62004-07-03 00:26:11 +00008061Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8062 Value *Cond = SI.getCondition();
8063 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8064 if (I->getOpcode() == Instruction::Add)
8065 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8066 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8067 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00008068 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00008069 AddRHS));
8070 SI.setOperand(0, I->getOperand(0));
8071 WorkList.push_back(I);
8072 return &SI;
8073 }
8074 }
8075 return 0;
8076}
8077
Chris Lattner220b0cf2006-03-05 00:22:33 +00008078/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8079/// is to leave as a vector operation.
8080static bool CheapToScalarize(Value *V, bool isConstant) {
8081 if (isa<ConstantAggregateZero>(V))
8082 return true;
8083 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8084 if (isConstant) return true;
8085 // If all elts are the same, we can extract.
8086 Constant *Op0 = C->getOperand(0);
8087 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8088 if (C->getOperand(i) != Op0)
8089 return false;
8090 return true;
8091 }
8092 Instruction *I = dyn_cast<Instruction>(V);
8093 if (!I) return false;
8094
8095 // Insert element gets simplified to the inserted element or is deleted if
8096 // this is constant idx extract element and its a constant idx insertelt.
8097 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8098 isa<ConstantInt>(I->getOperand(2)))
8099 return true;
8100 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8101 return true;
8102 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8103 if (BO->hasOneUse() &&
8104 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8105 CheapToScalarize(BO->getOperand(1), isConstant)))
8106 return true;
8107
8108 return false;
8109}
8110
Chris Lattner863bcff2006-05-25 23:48:38 +00008111/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8112/// elements into values that are larger than the #elts in the input.
8113static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8114 unsigned NElts = SVI->getType()->getNumElements();
8115 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8116 return std::vector<unsigned>(NElts, 0);
8117 if (isa<UndefValue>(SVI->getOperand(2)))
8118 return std::vector<unsigned>(NElts, 2*NElts);
8119
8120 std::vector<unsigned> Result;
8121 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8122 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8123 if (isa<UndefValue>(CP->getOperand(i)))
8124 Result.push_back(NElts*2); // undef -> 8
8125 else
Reid Spencerb83eb642006-10-20 07:07:24 +00008126 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00008127 return Result;
8128}
8129
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008130/// FindScalarElement - Given a vector and an element number, see if the scalar
8131/// value is already around as a register, for example if it were inserted then
8132/// extracted from the vector.
8133static Value *FindScalarElement(Value *V, unsigned EltNo) {
8134 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8135 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00008136 unsigned Width = PTy->getNumElements();
8137 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008138 return UndefValue::get(PTy->getElementType());
8139
8140 if (isa<UndefValue>(V))
8141 return UndefValue::get(PTy->getElementType());
8142 else if (isa<ConstantAggregateZero>(V))
8143 return Constant::getNullValue(PTy->getElementType());
8144 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8145 return CP->getOperand(EltNo);
8146 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8147 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00008148 if (!isa<ConstantInt>(III->getOperand(2)))
8149 return 0;
8150 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008151
8152 // If this is an insert to the element we are looking for, return the
8153 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00008154 if (EltNo == IIElt)
8155 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008156
8157 // Otherwise, the insertelement doesn't modify the value, recurse on its
8158 // vector input.
8159 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00008160 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00008161 unsigned InEl = getShuffleMask(SVI)[EltNo];
8162 if (InEl < Width)
8163 return FindScalarElement(SVI->getOperand(0), InEl);
8164 else if (InEl < Width*2)
8165 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8166 else
8167 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008168 }
8169
8170 // Otherwise, we don't know.
8171 return 0;
8172}
8173
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008174Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008175
Chris Lattner1f13c882006-03-31 18:25:14 +00008176 // If packed val is undef, replace extract with scalar undef.
8177 if (isa<UndefValue>(EI.getOperand(0)))
8178 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8179
8180 // If packed val is constant 0, replace extract with scalar 0.
8181 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8182 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8183
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008184 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8185 // If packed val is constant with uniform operands, replace EI
8186 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00008187 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008188 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00008189 if (C->getOperand(i) != op0) {
8190 op0 = 0;
8191 break;
8192 }
8193 if (op0)
8194 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008195 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00008196
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008197 // If extracting a specified index from the vector, see if we can recursively
8198 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00008199 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner867b99f2006-10-05 06:55:50 +00008200 // This instruction only demands the single element from the input vector.
8201 // If the input vector has a single use, simplify it based on this use
8202 // property.
Reid Spencerb83eb642006-10-20 07:07:24 +00008203 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00008204 if (EI.getOperand(0)->hasOneUse()) {
8205 uint64_t UndefElts;
8206 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00008207 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00008208 UndefElts)) {
8209 EI.setOperand(0, V);
8210 return &EI;
8211 }
8212 }
8213
Reid Spencerb83eb642006-10-20 07:07:24 +00008214 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008215 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00008216 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00008217
Chris Lattner73fa49d2006-05-25 22:53:38 +00008218 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008219 if (I->hasOneUse()) {
8220 // Push extractelement into predecessor operation if legal and
8221 // profitable to do so
8222 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00008223 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8224 if (CheapToScalarize(BO, isConstantElt)) {
8225 ExtractElementInst *newEI0 =
8226 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8227 EI.getName()+".lhs");
8228 ExtractElementInst *newEI1 =
8229 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8230 EI.getName()+".rhs");
8231 InsertNewInstBefore(newEI0, EI);
8232 InsertNewInstBefore(newEI1, EI);
8233 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8234 }
Reid Spencer3ed469c2006-11-02 20:25:50 +00008235 } else if (isa<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008236 Value *Ptr = InsertCastBefore(I->getOperand(0),
8237 PointerType::get(EI.getType()), EI);
8238 GetElementPtrInst *GEP =
8239 new GetElementPtrInst(Ptr, EI.getOperand(1),
8240 I->getName() + ".gep");
8241 InsertNewInstBefore(GEP, EI);
8242 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00008243 }
8244 }
8245 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8246 // Extracting the inserted element?
8247 if (IE->getOperand(2) == EI.getOperand(1))
8248 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8249 // If the inserted and extracted elements are constants, they must not
8250 // be the same value, extract from the pre-inserted value instead.
8251 if (isa<Constant>(IE->getOperand(2)) &&
8252 isa<Constant>(EI.getOperand(1))) {
8253 AddUsesToWorkList(EI);
8254 EI.setOperand(0, IE->getOperand(0));
8255 return &EI;
8256 }
8257 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8258 // If this is extracting an element from a shufflevector, figure out where
8259 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00008260 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8261 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00008262 Value *Src;
8263 if (SrcIdx < SVI->getType()->getNumElements())
8264 Src = SVI->getOperand(0);
8265 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8266 SrcIdx -= SVI->getType()->getNumElements();
8267 Src = SVI->getOperand(1);
8268 } else {
8269 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00008270 }
Chris Lattner867b99f2006-10-05 06:55:50 +00008271 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008272 }
8273 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00008274 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008275 return 0;
8276}
8277
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008278/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8279/// elements from either LHS or RHS, return the shuffle mask and true.
8280/// Otherwise, return false.
8281static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8282 std::vector<Constant*> &Mask) {
8283 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8284 "Invalid CollectSingleShuffleElements");
8285 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8286
8287 if (isa<UndefValue>(V)) {
8288 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8289 return true;
8290 } else if (V == LHS) {
8291 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00008292 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008293 return true;
8294 } else if (V == RHS) {
8295 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00008296 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008297 return true;
8298 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8299 // If this is an insert of an extract from some other vector, include it.
8300 Value *VecOp = IEI->getOperand(0);
8301 Value *ScalarOp = IEI->getOperand(1);
8302 Value *IdxOp = IEI->getOperand(2);
8303
Chris Lattnerd929f062006-04-27 21:14:21 +00008304 if (!isa<ConstantInt>(IdxOp))
8305 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00008306 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00008307
8308 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8309 // Okay, we can handle this if the vector we are insertinting into is
8310 // transitively ok.
8311 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8312 // If so, update the mask to reflect the inserted undef.
8313 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8314 return true;
8315 }
8316 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8317 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008318 EI->getOperand(0)->getType() == V->getType()) {
8319 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008320 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008321
8322 // This must be extracting from either LHS or RHS.
8323 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8324 // Okay, we can handle this if the vector we are insertinting into is
8325 // transitively ok.
8326 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8327 // If so, update the mask to reflect the inserted value.
8328 if (EI->getOperand(0) == LHS) {
8329 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00008330 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008331 } else {
8332 assert(EI->getOperand(0) == RHS);
8333 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00008334 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008335
8336 }
8337 return true;
8338 }
8339 }
8340 }
8341 }
8342 }
8343 // TODO: Handle shufflevector here!
8344
8345 return false;
8346}
8347
8348/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8349/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8350/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00008351static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008352 Value *&RHS) {
8353 assert(isa<PackedType>(V->getType()) &&
8354 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00008355 "Invalid shuffle!");
8356 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8357
8358 if (isa<UndefValue>(V)) {
8359 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8360 return V;
8361 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008362 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00008363 return V;
8364 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8365 // If this is an insert of an extract from some other vector, include it.
8366 Value *VecOp = IEI->getOperand(0);
8367 Value *ScalarOp = IEI->getOperand(1);
8368 Value *IdxOp = IEI->getOperand(2);
8369
8370 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8371 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8372 EI->getOperand(0)->getType() == V->getType()) {
8373 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00008374 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8375 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008376
8377 // Either the extracted from or inserted into vector must be RHSVec,
8378 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008379 if (EI->getOperand(0) == RHS || RHS == 0) {
8380 RHS = EI->getOperand(0);
8381 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008382 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00008383 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008384 return V;
8385 }
8386
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008387 if (VecOp == RHS) {
8388 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00008389 // Everything but the extracted element is replaced with the RHS.
8390 for (unsigned i = 0; i != NumElts; ++i) {
8391 if (i != InsertedIdx)
Reid Spencerb83eb642006-10-20 07:07:24 +00008392 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00008393 }
8394 return V;
8395 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008396
8397 // If this insertelement is a chain that comes from exactly these two
8398 // vectors, return the vector and the effective shuffle.
8399 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8400 return EI->getOperand(0);
8401
Chris Lattnerefb47352006-04-15 01:39:45 +00008402 }
8403 }
8404 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008405 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00008406
8407 // Otherwise, can't do anything fancy. Return an identity vector.
8408 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00008409 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00008410 return V;
8411}
8412
8413Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8414 Value *VecOp = IE.getOperand(0);
8415 Value *ScalarOp = IE.getOperand(1);
8416 Value *IdxOp = IE.getOperand(2);
8417
8418 // If the inserted element was extracted from some other vector, and if the
8419 // indexes are constant, try to turn this into a shufflevector operation.
8420 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8421 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8422 EI->getOperand(0)->getType() == IE.getType()) {
8423 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencerb83eb642006-10-20 07:07:24 +00008424 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8425 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008426
8427 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8428 return ReplaceInstUsesWith(IE, VecOp);
8429
8430 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8431 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8432
8433 // If we are extracting a value from a vector, then inserting it right
8434 // back into the same place, just use the input vector.
8435 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8436 return ReplaceInstUsesWith(IE, VecOp);
8437
8438 // We could theoretically do this for ANY input. However, doing so could
8439 // turn chains of insertelement instructions into a chain of shufflevector
8440 // instructions, and right now we do not merge shufflevectors. As such,
8441 // only do this in a situation where it is clear that there is benefit.
8442 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8443 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8444 // the values of VecOp, except then one read from EIOp0.
8445 // Build a new shuffle mask.
8446 std::vector<Constant*> Mask;
8447 if (isa<UndefValue>(VecOp))
8448 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8449 else {
8450 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerb83eb642006-10-20 07:07:24 +00008451 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattnerefb47352006-04-15 01:39:45 +00008452 NumVectorElts));
8453 }
Reid Spencerb83eb642006-10-20 07:07:24 +00008454 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008455 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8456 ConstantPacked::get(Mask));
8457 }
8458
8459 // If this insertelement isn't used by some other insertelement, turn it
8460 // (and any insertelements it points to), into one big shuffle.
8461 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8462 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008463 Value *RHS = 0;
8464 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8465 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8466 // We now have a shuffle of LHS, RHS, Mask.
8467 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00008468 }
8469 }
8470 }
8471
8472 return 0;
8473}
8474
8475
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008476Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8477 Value *LHS = SVI.getOperand(0);
8478 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00008479 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008480
8481 bool MadeChange = false;
8482
Chris Lattner867b99f2006-10-05 06:55:50 +00008483 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00008484 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008485 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8486
Chris Lattnerefb47352006-04-15 01:39:45 +00008487 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8488 // the undef, change them to undefs.
8489
Chris Lattner863bcff2006-05-25 23:48:38 +00008490 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8491 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8492 if (LHS == RHS || isa<UndefValue>(LHS)) {
8493 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008494 // shuffle(undef,undef,mask) -> undef.
8495 return ReplaceInstUsesWith(SVI, LHS);
8496 }
8497
Chris Lattner863bcff2006-05-25 23:48:38 +00008498 // Remap any references to RHS to use LHS.
8499 std::vector<Constant*> Elts;
8500 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00008501 if (Mask[i] >= 2*e)
Chris Lattner863bcff2006-05-25 23:48:38 +00008502 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008503 else {
8504 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8505 (Mask[i] < e && isa<UndefValue>(LHS)))
8506 Mask[i] = 2*e; // Turn into undef.
8507 else
8508 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerb83eb642006-10-20 07:07:24 +00008509 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008510 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008511 }
Chris Lattner863bcff2006-05-25 23:48:38 +00008512 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008513 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner863bcff2006-05-25 23:48:38 +00008514 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008515 LHS = SVI.getOperand(0);
8516 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008517 MadeChange = true;
8518 }
8519
Chris Lattner7b2e27922006-05-26 00:29:06 +00008520 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00008521 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00008522
Chris Lattner863bcff2006-05-25 23:48:38 +00008523 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8524 if (Mask[i] >= e*2) continue; // Ignore undef values.
8525 // Is this an identity shuffle of the LHS value?
8526 isLHSID &= (Mask[i] == i);
8527
8528 // Is this an identity shuffle of the RHS value?
8529 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00008530 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008531
Chris Lattner863bcff2006-05-25 23:48:38 +00008532 // Eliminate identity shuffles.
8533 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8534 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008535
Chris Lattner7b2e27922006-05-26 00:29:06 +00008536 // If the LHS is a shufflevector itself, see if we can combine it with this
8537 // one without producing an unusual shuffle. Here we are really conservative:
8538 // we are absolutely afraid of producing a shuffle mask not in the input
8539 // program, because the code gen may not be smart enough to turn a merged
8540 // shuffle into two specific shuffles: it may produce worse code. As such,
8541 // we only merge two shuffles if the result is one of the two input shuffle
8542 // masks. In this case, merging the shuffles just removes one instruction,
8543 // which we know is safe. This is good for things like turning:
8544 // (splat(splat)) -> splat.
8545 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8546 if (isa<UndefValue>(RHS)) {
8547 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8548
8549 std::vector<unsigned> NewMask;
8550 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8551 if (Mask[i] >= 2*e)
8552 NewMask.push_back(2*e);
8553 else
8554 NewMask.push_back(LHSMask[Mask[i]]);
8555
8556 // If the result mask is equal to the src shuffle or this shuffle mask, do
8557 // the replacement.
8558 if (NewMask == LHSMask || NewMask == Mask) {
8559 std::vector<Constant*> Elts;
8560 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8561 if (NewMask[i] >= e*2) {
8562 Elts.push_back(UndefValue::get(Type::UIntTy));
8563 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00008564 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008565 }
8566 }
8567 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8568 LHSSVI->getOperand(1),
8569 ConstantPacked::get(Elts));
8570 }
8571 }
8572 }
8573
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008574 return MadeChange ? &SVI : 0;
8575}
8576
8577
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008578
Chris Lattner62b14df2002-09-02 04:59:56 +00008579void InstCombiner::removeFromWorkList(Instruction *I) {
8580 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8581 WorkList.end());
8582}
8583
Chris Lattnerea1c4542004-12-08 23:43:58 +00008584
8585/// TryToSinkInstruction - Try to move the specified instruction from its
8586/// current block into the beginning of DestBlock, which can only happen if it's
8587/// safe to move the instruction past all of the instructions between it and the
8588/// end of its block.
8589static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8590 assert(I->hasOneUse() && "Invariants didn't hold!");
8591
Chris Lattner108e9022005-10-27 17:13:11 +00008592 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8593 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00008594
Chris Lattnerea1c4542004-12-08 23:43:58 +00008595 // Do not sink alloca instructions out of the entry block.
8596 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8597 return false;
8598
Chris Lattner96a52a62004-12-09 07:14:34 +00008599 // We can only sink load instructions if there is nothing between the load and
8600 // the end of block that could change the value.
8601 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00008602 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8603 Scan != E; ++Scan)
8604 if (Scan->mayWriteToMemory())
8605 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00008606 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00008607
8608 BasicBlock::iterator InsertPos = DestBlock->begin();
8609 while (isa<PHINode>(InsertPos)) ++InsertPos;
8610
Chris Lattner4bc5f802005-08-08 19:11:57 +00008611 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00008612 ++NumSunkInst;
8613 return true;
8614}
8615
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008616/// OptimizeConstantExpr - Given a constant expression and target data layout
8617/// information, symbolically evaluation the constant expr to something simpler
8618/// if possible.
8619static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8620 if (!TD) return CE;
8621
8622 Constant *Ptr = CE->getOperand(0);
8623 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8624 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8625 // If this is a constant expr gep that is effectively computing an
8626 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8627 bool isFoldableGEP = true;
8628 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8629 if (!isa<ConstantInt>(CE->getOperand(i)))
8630 isFoldableGEP = false;
8631 if (isFoldableGEP) {
8632 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8633 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencerb83eb642006-10-20 07:07:24 +00008634 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008635 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8636 return ConstantExpr::getCast(C, CE->getType());
8637 }
8638 }
8639
8640 return CE;
8641}
8642
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008643
8644/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8645/// all reachable code to the worklist.
8646///
8647/// This has a couple of tricks to make the code faster and more powerful. In
8648/// particular, we constant fold and DCE instructions as we go, to avoid adding
8649/// them to the worklist (this significantly speeds up instcombine on code where
8650/// many instructions are dead or constant). Additionally, if we find a branch
8651/// whose condition is a known constant, we only visit the reachable successors.
8652///
8653static void AddReachableCodeToWorklist(BasicBlock *BB,
8654 std::set<BasicBlock*> &Visited,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008655 std::vector<Instruction*> &WorkList,
8656 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008657 // We have now visited this block! If we've already been here, bail out.
8658 if (!Visited.insert(BB).second) return;
8659
8660 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8661 Instruction *Inst = BBI++;
8662
8663 // DCE instruction if trivially dead.
8664 if (isInstructionTriviallyDead(Inst)) {
8665 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00008666 DOUT << "IC: DCE: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008667 Inst->eraseFromParent();
8668 continue;
8669 }
8670
8671 // ConstantProp instruction if trivially constant.
8672 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008673 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8674 C = OptimizeConstantExpr(CE, TD);
Bill Wendlingb7427032006-11-26 09:46:52 +00008675 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008676 Inst->replaceAllUsesWith(C);
8677 ++NumConstProp;
8678 Inst->eraseFromParent();
8679 continue;
8680 }
8681
8682 WorkList.push_back(Inst);
8683 }
8684
8685 // Recursively visit successors. If this is a branch or switch on a constant,
8686 // only visit the reachable successor.
8687 TerminatorInst *TI = BB->getTerminator();
8688 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8689 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8690 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008691 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8692 TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008693 return;
8694 }
8695 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8696 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8697 // See if this is an explicit destination.
8698 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8699 if (SI->getCaseValue(i) == Cond) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008700 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008701 return;
8702 }
8703
8704 // Otherwise it is the default destination.
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008705 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008706 return;
8707 }
8708 }
8709
8710 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008711 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008712}
8713
Chris Lattner7e708292002-06-25 16:13:24 +00008714bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008715 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00008716 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00008717
Chris Lattnerb3d59702005-07-07 20:40:38 +00008718 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008719 // Do a depth-first traversal of the function, populate the worklist with
8720 // the reachable instructions. Ignore blocks that are not reachable. Keep
8721 // track of which blocks we visit.
Chris Lattnerb3d59702005-07-07 20:40:38 +00008722 std::set<BasicBlock*> Visited;
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008723 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00008724
Chris Lattnerb3d59702005-07-07 20:40:38 +00008725 // Do a quick scan over the function. If we find any blocks that are
8726 // unreachable, remove any instructions inside of them. This prevents
8727 // the instcombine code from having to deal with some bad special cases.
8728 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8729 if (!Visited.count(BB)) {
8730 Instruction *Term = BB->getTerminator();
8731 while (Term != BB->begin()) { // Remove instrs bottom-up
8732 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00008733
Bill Wendlingb7427032006-11-26 09:46:52 +00008734 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +00008735 ++NumDeadInst;
8736
8737 if (!I->use_empty())
8738 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8739 I->eraseFromParent();
8740 }
8741 }
8742 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008743
8744 while (!WorkList.empty()) {
8745 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8746 WorkList.pop_back();
8747
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008748 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008749 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008750 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00008751 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008752 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00008753 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00008754
Bill Wendlingb7427032006-11-26 09:46:52 +00008755 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00008756
8757 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00008758 removeFromWorkList(I);
8759 continue;
8760 }
Chris Lattner62b14df2002-09-02 04:59:56 +00008761
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008762 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner62b14df2002-09-02 04:59:56 +00008763 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008764 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8765 C = OptimizeConstantExpr(CE, TD);
Bill Wendlingb7427032006-11-26 09:46:52 +00008766 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +00008767
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008768 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008769 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00008770 ReplaceInstUsesWith(*I, C);
8771
Chris Lattner62b14df2002-09-02 04:59:56 +00008772 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008773 I->eraseFromParent();
Chris Lattner60610002003-10-07 15:17:02 +00008774 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008775 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00008776 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00008777
Chris Lattnerea1c4542004-12-08 23:43:58 +00008778 // See if we can trivially sink this instruction to a successor basic block.
8779 if (I->hasOneUse()) {
8780 BasicBlock *BB = I->getParent();
8781 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8782 if (UserParent != BB) {
8783 bool UserIsSuccessor = false;
8784 // See if the user is one of our successors.
8785 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8786 if (*SI == UserParent) {
8787 UserIsSuccessor = true;
8788 break;
8789 }
8790
8791 // If the user is one of our immediate successors, and if that successor
8792 // only has us as a predecessors (we'd have to split the critical edge
8793 // otherwise), we can keep going.
8794 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8795 next(pred_begin(UserParent)) == pred_end(UserParent))
8796 // Okay, the CFG is simple enough, try to sink this instruction.
8797 Changed |= TryToSinkInstruction(I, UserParent);
8798 }
8799 }
8800
Chris Lattner8a2a3112001-12-14 16:52:21 +00008801 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00008802 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00008803 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008804 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00008805 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +00008806 DOUT << "IC: Old = " << *I
8807 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +00008808
Chris Lattnerf523d062004-06-09 05:08:07 +00008809 // Everything uses the new instruction now.
8810 I->replaceAllUsesWith(Result);
8811
8812 // Push the new instruction and any users onto the worklist.
8813 WorkList.push_back(Result);
8814 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008815
8816 // Move the name to the new instruction first...
8817 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00008818 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008819
8820 // Insert the new instruction into the basic block...
8821 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00008822 BasicBlock::iterator InsertPos = I;
8823
8824 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8825 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8826 ++InsertPos;
8827
8828 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008829
Chris Lattner00d51312004-05-01 23:27:23 +00008830 // Make sure that we reprocess all operands now that we reduced their
8831 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00008832 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8833 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8834 WorkList.push_back(OpI);
8835
Chris Lattnerf523d062004-06-09 05:08:07 +00008836 // Instructions can end up on the worklist more than once. Make sure
8837 // we do not process an instruction that has been deleted.
8838 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008839
8840 // Erase the old instruction.
8841 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00008842 } else {
Bill Wendlingb7427032006-11-26 09:46:52 +00008843 DOUT << "IC: MOD = " << *I;
Chris Lattner0cea42a2004-03-13 23:54:27 +00008844
Chris Lattner90ac28c2002-08-02 19:29:35 +00008845 // If the instruction was modified, it's possible that it is now dead.
8846 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00008847 if (isInstructionTriviallyDead(I)) {
8848 // Make sure we process all operands now that we are reducing their
8849 // use counts.
8850 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8851 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8852 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008853
Chris Lattner00d51312004-05-01 23:27:23 +00008854 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008855 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008856 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00008857 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00008858 } else {
8859 WorkList.push_back(Result);
8860 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00008861 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00008862 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008863 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008864 }
8865 }
8866
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008867 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008868}
8869
Brian Gaeke96d4bf72004-07-27 17:43:21 +00008870FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008871 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008872}
Brian Gaeked0fde302003-11-11 22:41:34 +00008873