blob: 083acafe3264f9b181a3cd7a6b87a82129dfce79 [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000054#include <iostream>
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 Lattnerf57b8452002-04-27 06:56:12 +000065 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000066 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000069 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000070
Chris Lattner7bcc0e72004-02-28 05:22:00 +000071 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
73 /// now.
74 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000075 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000076 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000077 UI != UE; ++UI)
78 WorkList.push_back(cast<Instruction>(*UI));
79 }
80
Chris Lattner7bcc0e72004-02-28 05:22:00 +000081 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
83 ///
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
88 }
89
Chris Lattner62b14df2002-09-02 04:59:56 +000090 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092 public:
Chris Lattner7e708292002-06-25 16:13:24 +000093 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000094
Chris Lattner97e52e42002-04-28 21:27:06 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000096 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000097 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000098 }
99
Chris Lattner28977af2004-04-05 01:30:19 +0000100 TargetData &getTargetData() const { return *TD; }
101
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
104 // Return Value:
105 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000106 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000108 //
Chris Lattner7e708292002-06-25 16:13:24 +0000109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119
Chris Lattner574da9b2005-01-13 20:14:25 +0000120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000122 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner4d5542c2006-01-06 07:12:35 +0000123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000125 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000128 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000133 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000134 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000135 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000136 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000137 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000138 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000139 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000141 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000142
143 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000144 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000145
Chris Lattner9fe38862003-06-19 17:00:31 +0000146 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000147 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000148 bool transformConstExprCastCall(CallSite CS);
149
Chris Lattner28977af2004-04-05 01:30:19 +0000150 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000151 // InsertNewInstBefore - insert an instruction New before instruction Old
152 // in the program. Add the new instruction to the worklist.
153 //
Chris Lattner955f3312004-09-28 21:48:02 +0000154 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000155 assert(New && New->getParent() == 0 &&
156 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000157 BasicBlock *BB = Old.getParent();
158 BB->getInstList().insert(&Old, New); // Insert inst
159 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000160 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000161 }
162
Chris Lattner0c967662004-09-24 15:21:34 +0000163 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
164 /// This also adds the cast to the worklist. Finally, this returns the
165 /// cast.
166 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
167 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000168
Chris Lattnere2ed0572006-04-06 19:19:17 +0000169 if (Constant *CV = dyn_cast<Constant>(V))
170 return ConstantExpr::getCast(CV, Ty);
171
Chris Lattner0c967662004-09-24 15:21:34 +0000172 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
173 WorkList.push_back(C);
174 return C;
175 }
176
Chris Lattner8b170942002-08-09 23:47:40 +0000177 // ReplaceInstUsesWith - This method is to be used when an instruction is
178 // found to be dead, replacable with another preexisting expression. Here
179 // we add all uses of I to the worklist, replace all uses of I with the new
180 // value, then return I, so that the inst combiner will know that I was
181 // modified.
182 //
183 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000184 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000185 if (&I != V) {
186 I.replaceAllUsesWith(V);
187 return &I;
188 } else {
189 // If we are replacing the instruction with itself, this must be in a
190 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000191 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000192 return &I;
193 }
Chris Lattner8b170942002-08-09 23:47:40 +0000194 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000195
Chris Lattner6dce1a72006-02-07 06:56:34 +0000196 // UpdateValueUsesWith - This method is to be used when an value is
197 // found to be replacable with another preexisting expression or was
198 // updated. Here we add all uses of I to the worklist, replace all uses of
199 // I with the new value (unless the instruction was just updated), then
200 // return true, so that the inst combiner will know that I was modified.
201 //
202 bool UpdateValueUsesWith(Value *Old, Value *New) {
203 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
204 if (Old != New)
205 Old->replaceAllUsesWith(New);
206 if (Instruction *I = dyn_cast<Instruction>(Old))
207 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000208 if (Instruction *I = dyn_cast<Instruction>(New))
209 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000210 return true;
211 }
212
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000213 // EraseInstFromFunction - When dealing with an instruction that has side
214 // effects or produces a void value, we can't rely on DCE to delete the
215 // instruction. Instead, visit methods should return the value returned by
216 // this function.
217 Instruction *EraseInstFromFunction(Instruction &I) {
218 assert(I.use_empty() && "Cannot erase instruction that is used!");
219 AddUsesToWorkList(I);
220 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000221 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000222 return 0; // Don't do anything with FI
223 }
224
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000225 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000226 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
227 /// InsertBefore instruction. This is specialized a bit to avoid inserting
228 /// casts that are known to not do anything...
229 ///
230 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
231 Instruction *InsertBefore);
232
Chris Lattnerc8802d22003-03-11 00:12:48 +0000233 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000234 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000235 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000236
Chris Lattner255d8912006-02-11 09:31:47 +0000237 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
238 uint64_t &KnownZero, uint64_t &KnownOne,
239 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000240
241 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
242 // PHI node as operand #0, see if we can fold the instruction into the PHI
243 // (which is only possible if all operands to the PHI are constants).
244 Instruction *FoldOpIntoPhi(Instruction &I);
245
Chris Lattnerbac32862004-11-14 19:13:23 +0000246 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
247 // operator and they all are only used by the PHI, PHI together their
248 // inputs, and do the operation once, to the result of the PHI.
249 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
250
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000251 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
252 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000253
254 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
255 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000256 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
257 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000258 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner70074e02006-05-13 02:06:03 +0000259
260 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000261 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000262
Chris Lattnera6275cc2002-07-26 21:12:46 +0000263 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000264}
265
Chris Lattner4f98c562003-03-10 21:43:22 +0000266// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000267// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000268static unsigned getComplexity(Value *V) {
269 if (isa<Instruction>(V)) {
270 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000271 return 3;
272 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000273 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000274 if (isa<Argument>(V)) return 3;
275 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000276}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000277
Chris Lattnerc8802d22003-03-11 00:12:48 +0000278// isOnlyUse - Return true if this instruction will be deleted if we stop using
279// it.
280static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000281 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000282}
283
Chris Lattner4cb170c2004-02-23 06:38:22 +0000284// getPromotedType - Return the specified type promoted as it would be to pass
285// though a va_arg area...
286static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000287 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000288 case Type::SByteTyID:
289 case Type::ShortTyID: return Type::IntTy;
290 case Type::UByteTyID:
291 case Type::UShortTyID: return Type::UIntTy;
292 case Type::FloatTyID: return Type::DoubleTy;
293 default: return Ty;
294 }
295}
296
Chris Lattnereed48272005-09-13 00:40:14 +0000297/// isCast - If the specified operand is a CastInst or a constant expr cast,
298/// return the operand value, otherwise return null.
299static Value *isCast(Value *V) {
300 if (CastInst *I = dyn_cast<CastInst>(V))
301 return I->getOperand(0);
302 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
303 if (CE->getOpcode() == Instruction::Cast)
304 return CE->getOperand(0);
305 return 0;
306}
307
Chris Lattner33a61132006-05-06 09:00:16 +0000308enum CastType {
309 Noop = 0,
310 Truncate = 1,
311 Signext = 2,
312 Zeroext = 3
313};
314
315/// getCastType - In the future, we will split the cast instruction into these
316/// various types. Until then, we have to do the analysis here.
317static CastType getCastType(const Type *Src, const Type *Dest) {
318 assert(Src->isIntegral() && Dest->isIntegral() &&
319 "Only works on integral types!");
320 unsigned SrcSize = Src->getPrimitiveSizeInBits();
321 unsigned DestSize = Dest->getPrimitiveSizeInBits();
322
323 if (SrcSize == DestSize) return Noop;
324 if (SrcSize > DestSize) return Truncate;
325 if (Src->isSigned()) return Signext;
326 return Zeroext;
327}
328
329
330// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
331// instruction.
332//
333static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
334 const Type *DstTy, TargetData *TD) {
335
336 // It is legal to eliminate the instruction if casting A->B->A if the sizes
337 // are identical and the bits don't get reinterpreted (for example
338 // int->float->int would not be allowed).
339 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
340 return true;
341
342 // If we are casting between pointer and integer types, treat pointers as
343 // integers of the appropriate size for the code below.
344 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
345 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
346 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
347
348 // Allow free casting and conversion of sizes as long as the sign doesn't
349 // change...
350 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
351 CastType FirstCast = getCastType(SrcTy, MidTy);
352 CastType SecondCast = getCastType(MidTy, DstTy);
353
354 // Capture the effect of these two casts. If the result is a legal cast,
355 // the CastType is stored here, otherwise a special code is used.
356 static const unsigned CastResult[] = {
357 // First cast is noop
358 0, 1, 2, 3,
359 // First cast is a truncate
360 1, 1, 4, 4, // trunc->extend is not safe to eliminate
361 // First cast is a sign ext
362 2, 5, 2, 4, // signext->zeroext never ok
363 // First cast is a zero ext
364 3, 5, 3, 3,
365 };
366
367 unsigned Result = CastResult[FirstCast*4+SecondCast];
368 switch (Result) {
369 default: assert(0 && "Illegal table value!");
370 case 0:
371 case 1:
372 case 2:
373 case 3:
374 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
375 // truncates, we could eliminate more casts.
376 return (unsigned)getCastType(SrcTy, DstTy) == Result;
377 case 4:
378 return false; // Not possible to eliminate this here.
379 case 5:
380 // Sign or zero extend followed by truncate is always ok if the result
381 // is a truncate or noop.
382 CastType ResultCast = getCastType(SrcTy, DstTy);
383 if (ResultCast == Noop || ResultCast == Truncate)
384 return true;
385 // Otherwise we are still growing the value, we are only safe if the
386 // result will match the sign/zeroextendness of the result.
387 return ResultCast == FirstCast;
388 }
389 }
390
391 // If this is a cast from 'float -> double -> integer', cast from
392 // 'float -> integer' directly, as the value isn't changed by the
393 // float->double conversion.
394 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
395 DstTy->isIntegral() &&
396 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
397 return true;
398
399 // Packed type conversions don't modify bits.
400 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
401 return true;
402
403 return false;
404}
405
406/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
407/// in any code being generated. It does not require codegen if V is simple
408/// enough or if the cast can be folded into other casts.
409static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
410 if (V->getType() == Ty || isa<Constant>(V)) return false;
411
412 // If this is a noop cast, it isn't real codegen.
413 if (V->getType()->isLosslesslyConvertibleTo(Ty))
414 return false;
415
Chris Lattner01575b72006-05-25 23:24:33 +0000416 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000417 if (const CastInst *CI = dyn_cast<CastInst>(V))
418 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
419 TD))
420 return false;
421 return true;
422}
423
424/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
425/// InsertBefore instruction. This is specialized a bit to avoid inserting
426/// casts that are known to not do anything...
427///
428Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
429 Instruction *InsertBefore) {
430 if (V->getType() == DestTy) return V;
431 if (Constant *C = dyn_cast<Constant>(V))
432 return ConstantExpr::getCast(C, DestTy);
433
434 CastInst *CI = new CastInst(V, DestTy, V->getName());
435 InsertNewInstBefore(CI, *InsertBefore);
436 return CI;
437}
438
Chris Lattner4f98c562003-03-10 21:43:22 +0000439// SimplifyCommutative - This performs a few simplifications for commutative
440// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000441//
Chris Lattner4f98c562003-03-10 21:43:22 +0000442// 1. Order operands such that they are listed from right (least complex) to
443// left (most complex). This puts constants before unary operators before
444// binary operators.
445//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000446// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
447// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000448//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000449bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000450 bool Changed = false;
451 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
452 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000453
Chris Lattner4f98c562003-03-10 21:43:22 +0000454 if (!I.isAssociative()) return Changed;
455 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000456 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
457 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
458 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000459 Constant *Folded = ConstantExpr::get(I.getOpcode(),
460 cast<Constant>(I.getOperand(1)),
461 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000462 I.setOperand(0, Op->getOperand(0));
463 I.setOperand(1, Folded);
464 return true;
465 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
466 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
467 isOnlyUse(Op) && isOnlyUse(Op1)) {
468 Constant *C1 = cast<Constant>(Op->getOperand(1));
469 Constant *C2 = cast<Constant>(Op1->getOperand(1));
470
471 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000472 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000473 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
474 Op1->getOperand(0),
475 Op1->getName(), &I);
476 WorkList.push_back(New);
477 I.setOperand(0, New);
478 I.setOperand(1, Folded);
479 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000480 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000481 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000482 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000483}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000484
Chris Lattner8d969642003-03-10 23:06:50 +0000485// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
486// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000487//
Chris Lattner8d969642003-03-10 23:06:50 +0000488static inline Value *dyn_castNegVal(Value *V) {
489 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000490 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000491
Chris Lattner0ce85802004-12-14 20:08:06 +0000492 // Constants can be considered to be negated values if they can be folded.
493 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
494 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000495 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000496}
497
Chris Lattner8d969642003-03-10 23:06:50 +0000498static inline Value *dyn_castNotVal(Value *V) {
499 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000500 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000501
502 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000503 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000504 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000505 return 0;
506}
507
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508// dyn_castFoldableMul - If this value is a multiply that can be folded into
509// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000510// non-constant operand of the multiply, and set CST to point to the multiplier.
511// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000512//
Chris Lattner50af16a2004-11-13 19:50:12 +0000513static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000514 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000515 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000516 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000517 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000518 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000519 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000520 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000521 // The multiplier is really 1 << CST.
522 Constant *One = ConstantInt::get(V->getType(), 1);
523 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
524 return I->getOperand(0);
525 }
526 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000527 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000528}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000529
Chris Lattner574da9b2005-01-13 20:14:25 +0000530/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
531/// expression, return it.
532static User *dyn_castGetElementPtr(Value *V) {
533 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
534 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
535 if (CE->getOpcode() == Instruction::GetElementPtr)
536 return cast<User>(V);
537 return false;
538}
539
Chris Lattner955f3312004-09-28 21:48:02 +0000540// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000541static ConstantInt *AddOne(ConstantInt *C) {
542 return cast<ConstantInt>(ConstantExpr::getAdd(C,
543 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000544}
Chris Lattnera96879a2004-09-29 17:40:11 +0000545static ConstantInt *SubOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getSub(C,
547 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000548}
549
Chris Lattner255d8912006-02-11 09:31:47 +0000550/// GetConstantInType - Return a ConstantInt with the specified type and value.
551///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000552static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner255d8912006-02-11 09:31:47 +0000553 if (Ty->isUnsigned())
554 return ConstantUInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000555 else if (Ty->getTypeID() == Type::BoolTyID)
556 return ConstantBool::get(Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000557 int64_t SVal = Val;
558 SVal <<= 64-Ty->getPrimitiveSizeInBits();
559 SVal >>= 64-Ty->getPrimitiveSizeInBits();
560 return ConstantSInt::get(Ty, SVal);
561}
562
563
Chris Lattner68d5ff22006-02-09 07:38:58 +0000564/// ComputeMaskedBits - Determine which of the bits specified in Mask are
565/// known to be either zero or one and return them in the KnownZero/KnownOne
566/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
567/// processing.
568static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
569 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000570 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
571 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000572 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000573 // optimized based on the contradictory assumption that it is non-zero.
574 // Because instcombine aggressively folds operations with undef args anyway,
575 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000576 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
577 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000578 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000579 KnownZero = ~KnownOne & Mask;
580 return;
581 }
582
583 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000584 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000585 return; // Limit search depth.
586
587 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000588 Instruction *I = dyn_cast<Instruction>(V);
589 if (!I) return;
590
Chris Lattnere3158302006-05-04 17:33:35 +0000591 Mask &= V->getType()->getIntegralTypeMask();
592
Chris Lattner255d8912006-02-11 09:31:47 +0000593 switch (I->getOpcode()) {
594 case Instruction::And:
595 // If either the LHS or the RHS are Zero, the result is zero.
596 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
597 Mask &= ~KnownZero;
598 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
599 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
600 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
601
602 // Output known-1 bits are only known if set in both the LHS & RHS.
603 KnownOne &= KnownOne2;
604 // Output known-0 are known to be clear if zero in either the LHS | RHS.
605 KnownZero |= KnownZero2;
606 return;
607 case Instruction::Or:
608 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
609 Mask &= ~KnownOne;
610 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
611 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
612 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
613
614 // Output known-0 bits are only known if clear in both the LHS & RHS.
615 KnownZero &= KnownZero2;
616 // Output known-1 are known to be set if set in either the LHS | RHS.
617 KnownOne |= KnownOne2;
618 return;
619 case Instruction::Xor: {
620 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
621 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
622 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
623 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
624
625 // Output known-0 bits are known if clear or set in both the LHS & RHS.
626 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
627 // Output known-1 are known to be set if set in only one of the LHS, RHS.
628 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
629 KnownZero = KnownZeroOut;
630 return;
631 }
632 case Instruction::Select:
633 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
634 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
636 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
637
638 // Only known if known in both the LHS and RHS.
639 KnownOne &= KnownOne2;
640 KnownZero &= KnownZero2;
641 return;
642 case Instruction::Cast: {
643 const Type *SrcTy = I->getOperand(0)->getType();
644 if (!SrcTy->isIntegral()) return;
645
646 // If this is an integer truncate or noop, just look in the input.
647 if (SrcTy->getPrimitiveSizeInBits() >=
648 I->getType()->getPrimitiveSizeInBits()) {
649 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000650 return;
651 }
Chris Lattner68d5ff22006-02-09 07:38:58 +0000652
Chris Lattner255d8912006-02-11 09:31:47 +0000653 // Sign or Zero extension. Compute the bits in the result that are not
654 // present in the input.
655 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
656 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000657
Chris Lattner255d8912006-02-11 09:31:47 +0000658 // Handle zero extension.
659 if (!SrcTy->isSigned()) {
660 Mask &= SrcTy->getIntegralTypeMask();
661 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
662 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
663 // The top bits are known to be zero.
664 KnownZero |= NewBits;
665 } else {
666 // Sign extension.
667 Mask &= SrcTy->getIntegralTypeMask();
668 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
669 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000670
Chris Lattner255d8912006-02-11 09:31:47 +0000671 // If the sign bit of the input is known set or clear, then we know the
672 // top bits of the result.
673 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
674 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner68d5ff22006-02-09 07:38:58 +0000675 KnownZero |= NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000676 KnownOne &= ~NewBits;
677 } else if (KnownOne & InSignBit) { // Input sign bit known set
678 KnownOne |= NewBits;
679 KnownZero &= ~NewBits;
680 } else { // Input sign bit unknown
681 KnownZero &= ~NewBits;
682 KnownOne &= ~NewBits;
683 }
684 }
685 return;
686 }
687 case Instruction::Shl:
688 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
689 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
690 Mask >>= SA->getValue();
691 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
692 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
693 KnownZero <<= SA->getValue();
694 KnownOne <<= SA->getValue();
695 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
696 return;
697 }
698 break;
699 case Instruction::Shr:
700 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
701 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
702 // Compute the new bits that are at the top now.
703 uint64_t HighBits = (1ULL << SA->getValue())-1;
704 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
705
706 if (I->getType()->isUnsigned()) { // Unsigned shift right.
707 Mask <<= SA->getValue();
708 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
709 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
710 KnownZero >>= SA->getValue();
711 KnownOne >>= SA->getValue();
712 KnownZero |= HighBits; // high bits known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000713 } else {
Chris Lattner255d8912006-02-11 09:31:47 +0000714 Mask <<= SA->getValue();
715 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
716 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
717 KnownZero >>= SA->getValue();
718 KnownOne >>= SA->getValue();
719
720 // Handle the sign bits.
721 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
722 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
723
724 if (KnownZero & SignBit) { // New bits are known zero.
725 KnownZero |= HighBits;
726 } else if (KnownOne & SignBit) { // New bits are known one.
727 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000728 }
729 }
730 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000731 }
Chris Lattner255d8912006-02-11 09:31:47 +0000732 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000733 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000734}
735
736/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
737/// this predicate to simplify operations downstream. Mask is known to be zero
738/// for bits that V cannot have.
739static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000740 uint64_t KnownZero, KnownOne;
741 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
742 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
743 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000744}
745
Chris Lattner255d8912006-02-11 09:31:47 +0000746/// ShrinkDemandedConstant - Check to see if the specified operand of the
747/// specified instruction is a constant integer. If so, check to see if there
748/// are any bits set in the constant that are not demanded. If so, shrink the
749/// constant and return true.
750static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
751 uint64_t Demanded) {
752 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
753 if (!OpC) return false;
754
755 // If there are no bits set that aren't demanded, nothing to do.
756 if ((~Demanded & OpC->getZExtValue()) == 0)
757 return false;
758
759 // This is producing any bits that are not needed, shrink the RHS.
760 uint64_t Val = Demanded & OpC->getZExtValue();
761 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
762 return true;
763}
764
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000765// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
766// set of known zero and one bits, compute the maximum and minimum values that
767// could have the specified known zero and known one bits, returning them in
768// min/max.
769static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
770 uint64_t KnownZero,
771 uint64_t KnownOne,
772 int64_t &Min, int64_t &Max) {
773 uint64_t TypeBits = Ty->getIntegralTypeMask();
774 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
775
776 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
777
778 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
779 // bit if it is unknown.
780 Min = KnownOne;
781 Max = KnownOne|UnknownBits;
782
783 if (SignBit & UnknownBits) { // Sign bit is unknown
784 Min |= SignBit;
785 Max &= ~SignBit;
786 }
787
788 // Sign extend the min/max values.
789 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
790 Min = (Min << ShAmt) >> ShAmt;
791 Max = (Max << ShAmt) >> ShAmt;
792}
793
794// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
795// a set of known zero and one bits, compute the maximum and minimum values that
796// could have the specified known zero and known one bits, returning them in
797// min/max.
798static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
799 uint64_t KnownZero,
800 uint64_t KnownOne,
801 uint64_t &Min,
802 uint64_t &Max) {
803 uint64_t TypeBits = Ty->getIntegralTypeMask();
804 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
805
806 // The minimum value is when the unknown bits are all zeros.
807 Min = KnownOne;
808 // The maximum value is when the unknown bits are all ones.
809 Max = KnownOne|UnknownBits;
810}
Chris Lattner255d8912006-02-11 09:31:47 +0000811
812
813/// SimplifyDemandedBits - Look at V. At this point, we know that only the
814/// DemandedMask bits of the result of V are ever used downstream. If we can
815/// use this information to simplify V, do so and return true. Otherwise,
816/// analyze the expression and return a mask of KnownOne and KnownZero bits for
817/// the expression (used to simplify the caller). The KnownZero/One bits may
818/// only be accurate for those bits in the DemandedMask.
819bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
820 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000821 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000822 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
823 // We know all of the bits for a constant!
824 KnownOne = CI->getZExtValue() & DemandedMask;
825 KnownZero = ~KnownOne & DemandedMask;
826 return false;
827 }
828
829 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000830 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000831 if (Depth != 0) { // Not at the root.
832 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
833 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000834 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000835 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000836 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000837 // just set the DemandedMask to all bits.
838 DemandedMask = V->getType()->getIntegralTypeMask();
839 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000840 if (V != UndefValue::get(V->getType()))
841 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
842 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000843 } else if (Depth == 6) { // Limit search depth.
844 return false;
845 }
846
847 Instruction *I = dyn_cast<Instruction>(V);
848 if (!I) return false; // Only analyze instructions.
849
Chris Lattnere3158302006-05-04 17:33:35 +0000850 DemandedMask &= V->getType()->getIntegralTypeMask();
851
Chris Lattner255d8912006-02-11 09:31:47 +0000852 uint64_t KnownZero2, KnownOne2;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000853 switch (I->getOpcode()) {
854 default: break;
855 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000856 // If either the LHS or the RHS are Zero, the result is zero.
857 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
858 KnownZero, KnownOne, Depth+1))
859 return true;
860 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
861
862 // If something is known zero on the RHS, the bits aren't demanded on the
863 // LHS.
864 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
865 KnownZero2, KnownOne2, Depth+1))
866 return true;
867 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
868
869 // If all of the demanded bits are known one on one side, return the other.
870 // These bits cannot contribute to the result of the 'and'.
871 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
874 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000875
876 // If all of the demanded bits in the inputs are known zeros, return zero.
877 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
878 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
879
Chris Lattner255d8912006-02-11 09:31:47 +0000880 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000881 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000882 return UpdateValueUsesWith(I, I);
883
884 // Output known-1 bits are only known if set in both the LHS & RHS.
885 KnownOne &= KnownOne2;
886 // Output known-0 are known to be clear if zero in either the LHS | RHS.
887 KnownZero |= KnownZero2;
888 break;
889 case Instruction::Or:
890 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
891 KnownZero, KnownOne, Depth+1))
892 return true;
893 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
894 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
895 KnownZero2, KnownOne2, Depth+1))
896 return true;
897 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
898
899 // If all of the demanded bits are known zero on one side, return the other.
900 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000901 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000902 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000903 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000904 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000905
906 // If all of the potentially set bits on one side are known to be set on
907 // the other side, just use the 'other' side.
908 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
909 (DemandedMask & (~KnownZero)))
910 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000911 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
912 (DemandedMask & (~KnownZero2)))
913 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000914
915 // If the RHS is a constant, see if we can simplify it.
916 if (ShrinkDemandedConstant(I, 1, DemandedMask))
917 return UpdateValueUsesWith(I, I);
918
919 // Output known-0 bits are only known if clear in both the LHS & RHS.
920 KnownZero &= KnownZero2;
921 // Output known-1 are known to be set if set in either the LHS | RHS.
922 KnownOne |= KnownOne2;
923 break;
924 case Instruction::Xor: {
925 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
926 KnownZero, KnownOne, Depth+1))
927 return true;
928 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
929 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
930 KnownZero2, KnownOne2, Depth+1))
931 return true;
932 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
933
934 // If all of the demanded bits are known zero on one side, return the other.
935 // These bits cannot contribute to the result of the 'xor'.
936 if ((DemandedMask & KnownZero) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(0));
938 if ((DemandedMask & KnownZero2) == DemandedMask)
939 return UpdateValueUsesWith(I, I->getOperand(1));
940
941 // Output known-0 bits are known if clear or set in both the LHS & RHS.
942 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
943 // Output known-1 are known to be set if set in only one of the LHS, RHS.
944 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
945
946 // If all of the unknown bits are known to be zero on one side or the other
947 // (but not both) turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000948 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner255d8912006-02-11 09:31:47 +0000949 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
950 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
951 Instruction *Or =
952 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
953 I->getName());
954 InsertNewInstBefore(Or, *I);
955 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000956 }
957 }
Chris Lattner255d8912006-02-11 09:31:47 +0000958
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000959 // If all of the demanded bits on one side are known, and all of the set
960 // bits on that side are also known to be set on the other side, turn this
961 // into an AND, as we know the bits will be cleared.
962 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
963 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
964 if ((KnownOne & KnownOne2) == KnownOne) {
965 Constant *AndC = GetConstantInType(I->getType(),
966 ~KnownOne & DemandedMask);
967 Instruction *And =
968 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
969 InsertNewInstBefore(And, *I);
970 return UpdateValueUsesWith(I, And);
971 }
972 }
973
Chris Lattner255d8912006-02-11 09:31:47 +0000974 // If the RHS is a constant, see if we can simplify it.
975 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
976 if (ShrinkDemandedConstant(I, 1, DemandedMask))
977 return UpdateValueUsesWith(I, I);
978
979 KnownZero = KnownZeroOut;
980 KnownOne = KnownOneOut;
981 break;
982 }
983 case Instruction::Select:
984 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
985 KnownZero, KnownOne, Depth+1))
986 return true;
987 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
988 KnownZero2, KnownOne2, Depth+1))
989 return true;
990 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
991 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
992
993 // If the operands are constants, see if we can simplify them.
994 if (ShrinkDemandedConstant(I, 1, DemandedMask))
995 return UpdateValueUsesWith(I, I);
996 if (ShrinkDemandedConstant(I, 2, DemandedMask))
997 return UpdateValueUsesWith(I, I);
998
999 // Only known if known in both the LHS and RHS.
1000 KnownOne &= KnownOne2;
1001 KnownZero &= KnownZero2;
1002 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001003 case Instruction::Cast: {
1004 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +00001005 if (!SrcTy->isIntegral()) return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001006
Chris Lattner255d8912006-02-11 09:31:47 +00001007 // If this is an integer truncate or noop, just look in the input.
1008 if (SrcTy->getPrimitiveSizeInBits() >=
1009 I->getType()->getPrimitiveSizeInBits()) {
1010 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1011 KnownZero, KnownOne, Depth+1))
1012 return true;
1013 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1014 break;
1015 }
1016
1017 // Sign or Zero extension. Compute the bits in the result that are not
1018 // present in the input.
1019 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1020 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1021
1022 // Handle zero extension.
1023 if (!SrcTy->isSigned()) {
1024 DemandedMask &= SrcTy->getIntegralTypeMask();
1025 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1026 KnownZero, KnownOne, Depth+1))
1027 return true;
1028 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1029 // The top bits are known to be zero.
1030 KnownZero |= NewBits;
1031 } else {
1032 // Sign extension.
Chris Lattnerf345fe42006-02-13 22:41:07 +00001033 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1034 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1035
1036 // If any of the sign extended bits are demanded, we know that the sign
1037 // bit is demanded.
1038 if (NewBits & DemandedMask)
1039 InputDemandedBits |= InSignBit;
1040
1041 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner255d8912006-02-11 09:31:47 +00001042 KnownZero, KnownOne, Depth+1))
1043 return true;
1044 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1045
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001048
Chris Lattner255d8912006-02-11 09:31:47 +00001049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
1051 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner6dce1a72006-02-07 06:56:34 +00001052 // Convert to unsigned first.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001053 Instruction *NewVal;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001054 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattnerd89d8882006-02-07 19:07:40 +00001055 I->getOperand(0)->getName());
1056 InsertNewInstBefore(NewVal, *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001057 // Then cast that to the destination type.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001058 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1059 InsertNewInstBefore(NewVal, *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001060 return UpdateValueUsesWith(I, NewVal);
Chris Lattner255d8912006-02-11 09:31:47 +00001061 } else if (KnownOne & InSignBit) { // Input sign bit known set
1062 KnownOne |= NewBits;
1063 KnownZero &= ~NewBits;
1064 } else { // Input sign bit unknown
1065 KnownZero &= ~NewBits;
1066 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001067 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001068 }
Chris Lattner255d8912006-02-11 09:31:47 +00001069 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001070 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001071 case Instruction::Shl:
Chris Lattner255d8912006-02-11 09:31:47 +00001072 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1073 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1074 KnownZero, KnownOne, Depth+1))
1075 return true;
1076 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1077 KnownZero <<= SA->getValue();
1078 KnownOne <<= SA->getValue();
1079 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1080 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001081 break;
1082 case Instruction::Shr:
Chris Lattner255d8912006-02-11 09:31:47 +00001083 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1084 unsigned ShAmt = SA->getValue();
1085
1086 // Compute the new bits that are at the top now.
1087 uint64_t HighBits = (1ULL << ShAmt)-1;
1088 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +00001089 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner255d8912006-02-11 09:31:47 +00001090 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001091 if (SimplifyDemandedBits(I->getOperand(0),
1092 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001093 KnownZero, KnownOne, Depth+1))
1094 return true;
1095 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001096 KnownZero &= TypeMask;
1097 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +00001098 KnownZero >>= ShAmt;
1099 KnownOne >>= ShAmt;
1100 KnownZero |= HighBits; // high bits known zero.
1101 } else { // Signed shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001102 if (SimplifyDemandedBits(I->getOperand(0),
1103 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001104 KnownZero, KnownOne, Depth+1))
1105 return true;
1106 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001107 KnownZero &= TypeMask;
1108 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +00001109 KnownZero >>= SA->getValue();
1110 KnownOne >>= SA->getValue();
1111
1112 // Handle the sign bits.
1113 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1114 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1115
1116 // If the input sign bit is known to be zero, or if none of the top bits
1117 // are demanded, turn this into an unsigned shift right.
1118 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1119 // Convert the input to unsigned.
1120 Instruction *NewVal;
1121 NewVal = new CastInst(I->getOperand(0),
1122 I->getType()->getUnsignedVersion(),
1123 I->getOperand(0)->getName());
1124 InsertNewInstBefore(NewVal, *I);
1125 // Perform the unsigned shift right.
1126 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1127 InsertNewInstBefore(NewVal, *I);
1128 // Then cast that to the destination type.
1129 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1130 InsertNewInstBefore(NewVal, *I);
1131 return UpdateValueUsesWith(I, NewVal);
1132 } else if (KnownOne & SignBit) { // New bits are known one.
1133 KnownOne |= HighBits;
1134 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001135 }
Chris Lattner255d8912006-02-11 09:31:47 +00001136 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001137 break;
1138 }
Chris Lattner255d8912006-02-11 09:31:47 +00001139
1140 // If the client is only demanding bits that we know, return the known
1141 // constant.
1142 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1143 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001144 return false;
1145}
1146
Chris Lattner955f3312004-09-28 21:48:02 +00001147// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1148// true when both operands are equal...
1149//
1150static bool isTrueWhenEqual(Instruction &I) {
1151 return I.getOpcode() == Instruction::SetEQ ||
1152 I.getOpcode() == Instruction::SetGE ||
1153 I.getOpcode() == Instruction::SetLE;
1154}
Chris Lattner564a7272003-08-13 19:01:45 +00001155
1156/// AssociativeOpt - Perform an optimization on an associative operator. This
1157/// function is designed to check a chain of associative operators for a
1158/// potential to apply a certain optimization. Since the optimization may be
1159/// applicable if the expression was reassociated, this checks the chain, then
1160/// reassociates the expression as necessary to expose the optimization
1161/// opportunity. This makes use of a special Functor, which must define
1162/// 'shouldApply' and 'apply' methods.
1163///
1164template<typename Functor>
1165Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1166 unsigned Opcode = Root.getOpcode();
1167 Value *LHS = Root.getOperand(0);
1168
1169 // Quick check, see if the immediate LHS matches...
1170 if (F.shouldApply(LHS))
1171 return F.apply(Root);
1172
1173 // Otherwise, if the LHS is not of the same opcode as the root, return.
1174 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001175 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001176 // Should we apply this transform to the RHS?
1177 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1178
1179 // If not to the RHS, check to see if we should apply to the LHS...
1180 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1181 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1182 ShouldApply = true;
1183 }
1184
1185 // If the functor wants to apply the optimization to the RHS of LHSI,
1186 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1187 if (ShouldApply) {
1188 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001189
Chris Lattner564a7272003-08-13 19:01:45 +00001190 // Now all of the instructions are in the current basic block, go ahead
1191 // and perform the reassociation.
1192 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1193
1194 // First move the selected RHS to the LHS of the root...
1195 Root.setOperand(0, LHSI->getOperand(1));
1196
1197 // Make what used to be the LHS of the root be the user of the root...
1198 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001199 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001200 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1201 return 0;
1202 }
Chris Lattner65725312004-04-16 18:08:07 +00001203 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001204 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001205 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1206 BasicBlock::iterator ARI = &Root; ++ARI;
1207 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1208 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001209
1210 // Now propagate the ExtraOperand down the chain of instructions until we
1211 // get to LHSI.
1212 while (TmpLHSI != LHSI) {
1213 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001214 // Move the instruction to immediately before the chain we are
1215 // constructing to avoid breaking dominance properties.
1216 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1217 BB->getInstList().insert(ARI, NextLHSI);
1218 ARI = NextLHSI;
1219
Chris Lattner564a7272003-08-13 19:01:45 +00001220 Value *NextOp = NextLHSI->getOperand(1);
1221 NextLHSI->setOperand(1, ExtraOperand);
1222 TmpLHSI = NextLHSI;
1223 ExtraOperand = NextOp;
1224 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001225
Chris Lattner564a7272003-08-13 19:01:45 +00001226 // Now that the instructions are reassociated, have the functor perform
1227 // the transformation...
1228 return F.apply(Root);
1229 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001230
Chris Lattner564a7272003-08-13 19:01:45 +00001231 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1232 }
1233 return 0;
1234}
1235
1236
1237// AddRHS - Implements: X + X --> X << 1
1238struct AddRHS {
1239 Value *RHS;
1240 AddRHS(Value *rhs) : RHS(rhs) {}
1241 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1242 Instruction *apply(BinaryOperator &Add) const {
1243 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1244 ConstantInt::get(Type::UByteTy, 1));
1245 }
1246};
1247
1248// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1249// iff C1&C2 == 0
1250struct AddMaskingAnd {
1251 Constant *C2;
1252 AddMaskingAnd(Constant *c) : C2(c) {}
1253 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001254 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001255 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001256 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001257 }
1258 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001259 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001260 }
1261};
1262
Chris Lattner6e7ba452005-01-01 16:22:27 +00001263static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001264 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001265 if (isa<CastInst>(I)) {
1266 if (Constant *SOC = dyn_cast<Constant>(SO))
1267 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001268
Chris Lattner6e7ba452005-01-01 16:22:27 +00001269 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1270 SO->getName() + ".cast"), I);
1271 }
1272
Chris Lattner2eefe512004-04-09 19:05:30 +00001273 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001274 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1275 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001276
Chris Lattner2eefe512004-04-09 19:05:30 +00001277 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1278 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001279 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1280 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001281 }
1282
1283 Value *Op0 = SO, *Op1 = ConstOperand;
1284 if (!ConstIsRHS)
1285 std::swap(Op0, Op1);
1286 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001287 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1288 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1289 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1290 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001291 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001292 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001293 abort();
1294 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001295 return IC->InsertNewInstBefore(New, I);
1296}
1297
1298// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1299// constant as the other operand, try to fold the binary operator into the
1300// select arguments. This also works for Cast instructions, which obviously do
1301// not have a second operand.
1302static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1303 InstCombiner *IC) {
1304 // Don't modify shared select instructions
1305 if (!SI->hasOneUse()) return 0;
1306 Value *TV = SI->getOperand(1);
1307 Value *FV = SI->getOperand(2);
1308
1309 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001310 // Bool selects with constant operands can be folded to logical ops.
1311 if (SI->getType() == Type::BoolTy) return 0;
1312
Chris Lattner6e7ba452005-01-01 16:22:27 +00001313 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1314 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1315
1316 return new SelectInst(SI->getCondition(), SelectTrueVal,
1317 SelectFalseVal);
1318 }
1319 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001320}
1321
Chris Lattner4e998b22004-09-29 05:07:12 +00001322
1323/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1324/// node as operand #0, see if we can fold the instruction into the PHI (which
1325/// is only possible if all operands to the PHI are constants).
1326Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1327 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001328 unsigned NumPHIValues = PN->getNumIncomingValues();
1329 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1330 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001331
1332 // Check to see if all of the operands of the PHI are constants. If not, we
1333 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +00001334 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +00001335 if (!isa<Constant>(PN->getIncomingValue(i)))
1336 return 0;
1337
1338 // Okay, we can do the transformation: create the new PHI node.
1339 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1340 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001341 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001342 InsertNewInstBefore(NewPN, *PN);
1343
1344 // Next, add all of the operands to the PHI.
1345 if (I.getNumOperands() == 2) {
1346 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001347 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001348 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1349 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1350 PN->getIncomingBlock(i));
1351 }
1352 } else {
1353 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1354 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001355 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001356 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1357 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1358 PN->getIncomingBlock(i));
1359 }
1360 }
1361 return ReplaceInstUsesWith(I, NewPN);
1362}
1363
Chris Lattner7e708292002-06-25 16:13:24 +00001364Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001365 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001366 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001367
Chris Lattner66331a42004-04-10 22:01:55 +00001368 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001369 // X + undef -> undef
1370 if (isa<UndefValue>(RHS))
1371 return ReplaceInstUsesWith(I, RHS);
1372
Chris Lattner66331a42004-04-10 22:01:55 +00001373 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001374 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1375 if (RHSC->isNullValue())
1376 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001377 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1378 if (CFP->isExactlyValue(-0.0))
1379 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001380 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001381
Chris Lattner66331a42004-04-10 22:01:55 +00001382 // X + (signbit) --> X ^ signbit
1383 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +00001384 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001385 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001386 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +00001387 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001388
1389 if (isa<PHINode>(LHS))
1390 if (Instruction *NV = FoldOpIntoPhi(I))
1391 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001392
Chris Lattner4f637d42006-01-06 17:59:59 +00001393 ConstantInt *XorRHS = 0;
1394 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001395 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1396 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1397 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1398 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1399
1400 uint64_t C0080Val = 1ULL << 31;
1401 int64_t CFF80Val = -C0080Val;
1402 unsigned Size = 32;
1403 do {
1404 if (TySizeBits > Size) {
1405 bool Found = false;
1406 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1407 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1408 if (RHSSExt == CFF80Val) {
1409 if (XorRHS->getZExtValue() == C0080Val)
1410 Found = true;
1411 } else if (RHSZExt == C0080Val) {
1412 if (XorRHS->getSExtValue() == CFF80Val)
1413 Found = true;
1414 }
1415 if (Found) {
1416 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001417 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001418 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001419 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001420 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001421 Size = 0; // Not a sign ext, but can't be any others either.
1422 goto FoundSExt;
1423 }
1424 }
1425 Size >>= 1;
1426 C0080Val >>= Size;
1427 CFF80Val >>= Size;
1428 } while (Size >= 8);
1429
1430FoundSExt:
1431 const Type *MiddleType = 0;
1432 switch (Size) {
1433 default: break;
1434 case 32: MiddleType = Type::IntTy; break;
1435 case 16: MiddleType = Type::ShortTy; break;
1436 case 8: MiddleType = Type::SByteTy; break;
1437 }
1438 if (MiddleType) {
1439 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1440 InsertNewInstBefore(NewTrunc, I);
1441 return new CastInst(NewTrunc, I.getType());
1442 }
1443 }
Chris Lattner66331a42004-04-10 22:01:55 +00001444 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001445
Chris Lattner564a7272003-08-13 19:01:45 +00001446 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001447 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001448 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001449
1450 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1451 if (RHSI->getOpcode() == Instruction::Sub)
1452 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1453 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1454 }
1455 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1456 if (LHSI->getOpcode() == Instruction::Sub)
1457 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1458 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1459 }
Robert Bocchino71698282004-07-27 21:02:21 +00001460 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001461
Chris Lattner5c4afb92002-05-08 22:46:53 +00001462 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001463 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001464 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001465
1466 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001467 if (!isa<Constant>(RHS))
1468 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001469 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001470
Misha Brukmanfd939082005-04-21 23:48:37 +00001471
Chris Lattner50af16a2004-11-13 19:50:12 +00001472 ConstantInt *C2;
1473 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1474 if (X == RHS) // X*C + X --> X * (C+1)
1475 return BinaryOperator::createMul(RHS, AddOne(C2));
1476
1477 // X*C1 + X*C2 --> X * (C1+C2)
1478 ConstantInt *C1;
1479 if (X == dyn_castFoldableMul(RHS, C1))
1480 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001481 }
1482
1483 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001484 if (dyn_castFoldableMul(RHS, C2) == LHS)
1485 return BinaryOperator::createMul(LHS, AddOne(C2));
1486
Chris Lattnerad3448c2003-02-18 19:57:07 +00001487
Chris Lattner564a7272003-08-13 19:01:45 +00001488 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001489 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001490 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001491
Chris Lattner6b032052003-10-02 15:11:26 +00001492 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001493 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001494 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1495 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1496 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001497 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001498
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001499 // (X & FF00) + xx00 -> (X+xx00) & FF00
1500 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1501 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1502 if (Anded == CRHS) {
1503 // See if all bits from the first bit set in the Add RHS up are included
1504 // in the mask. First, get the rightmost bit.
1505 uint64_t AddRHSV = CRHS->getRawValue();
1506
1507 // Form a mask of all bits from the lowest bit added through the top.
1508 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001509 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001510
1511 // See if the and mask includes all of these bits.
1512 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001513
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001514 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1515 // Okay, the xform is safe. Insert the new add pronto.
1516 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1517 LHS->getName()), I);
1518 return BinaryOperator::createAnd(NewAdd, C2);
1519 }
1520 }
1521 }
1522
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001523 // Try to fold constant add into select arguments.
1524 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001525 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001526 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001527 }
1528
Chris Lattner7e708292002-06-25 16:13:24 +00001529 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001530}
1531
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001532// isSignBit - Return true if the value represented by the constant only has the
1533// highest order bit set.
1534static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001535 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +00001536 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001537}
1538
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001539/// RemoveNoopCast - Strip off nonconverting casts from the value.
1540///
1541static Value *RemoveNoopCast(Value *V) {
1542 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1543 const Type *CTy = CI->getType();
1544 const Type *OpTy = CI->getOperand(0)->getType();
1545 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001546 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001547 return RemoveNoopCast(CI->getOperand(0));
1548 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1549 return RemoveNoopCast(CI->getOperand(0));
1550 }
1551 return V;
1552}
1553
Chris Lattner7e708292002-06-25 16:13:24 +00001554Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001555 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001556
Chris Lattner233f7dc2002-08-12 21:17:25 +00001557 if (Op0 == Op1) // sub X, X -> 0
1558 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001559
Chris Lattner233f7dc2002-08-12 21:17:25 +00001560 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001561 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001562 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001563
Chris Lattnere87597f2004-10-16 18:11:37 +00001564 if (isa<UndefValue>(Op0))
1565 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1566 if (isa<UndefValue>(Op1))
1567 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1568
Chris Lattnerd65460f2003-11-05 01:06:05 +00001569 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1570 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001571 if (C->isAllOnesValue())
1572 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001573
Chris Lattnerd65460f2003-11-05 01:06:05 +00001574 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001575 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001576 if (match(Op1, m_Not(m_Value(X))))
1577 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001578 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001579 // -((uint)X >> 31) -> ((int)X >> 31)
1580 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001581 if (C->isNullValue()) {
1582 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1583 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001584 if (SI->getOpcode() == Instruction::Shr)
1585 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1586 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001587 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001588 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001589 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001590 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001591 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +00001592 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001593 // Ok, the transformation is safe. Insert a cast of the incoming
1594 // value, then the new shift, then the new cast.
1595 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1596 SI->getOperand(0)->getName());
1597 Value *InV = InsertNewInstBefore(FirstCast, I);
1598 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1599 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001600 if (NewShift->getType() == I.getType())
1601 return NewShift;
1602 else {
1603 InV = InsertNewInstBefore(NewShift, I);
1604 return new CastInst(NewShift, I.getType());
1605 }
Chris Lattner9c290672004-03-12 23:53:13 +00001606 }
1607 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001608 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001609
1610 // Try to fold constant sub into select arguments.
1611 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001612 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001613 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001614
1615 if (isa<PHINode>(Op0))
1616 if (Instruction *NV = FoldOpIntoPhi(I))
1617 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001618 }
1619
Chris Lattner43d84d62005-04-07 16:15:25 +00001620 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1621 if (Op1I->getOpcode() == Instruction::Add &&
1622 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001623 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001624 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001625 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001626 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001627 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1628 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1629 // C1-(X+C2) --> (C1-C2)-X
1630 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1631 Op1I->getOperand(0));
1632 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001633 }
1634
Chris Lattnerfd059242003-10-15 16:48:29 +00001635 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001636 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1637 // is not used by anyone else...
1638 //
Chris Lattner0517e722004-02-02 20:09:56 +00001639 if (Op1I->getOpcode() == Instruction::Sub &&
1640 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001641 // Swap the two operands of the subexpr...
1642 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1643 Op1I->setOperand(0, IIOp1);
1644 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001645
Chris Lattnera2881962003-02-18 19:28:33 +00001646 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001647 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001648 }
1649
1650 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1651 //
1652 if (Op1I->getOpcode() == Instruction::And &&
1653 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1654 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1655
Chris Lattnerf523d062004-06-09 05:08:07 +00001656 Value *NewNot =
1657 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001658 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001659 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001660
Chris Lattner91ccc152004-10-06 15:08:25 +00001661 // -(X sdiv C) -> (X sdiv -C)
1662 if (Op1I->getOpcode() == Instruction::Div)
1663 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +00001664 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001665 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001666 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001667 ConstantExpr::getNeg(DivRHS));
1668
Chris Lattnerad3448c2003-02-18 19:57:07 +00001669 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001670 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001671 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001672 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001673 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001674 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001675 }
Chris Lattner40371712002-05-09 01:29:19 +00001676 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001677 }
Chris Lattnera2881962003-02-18 19:28:33 +00001678
Chris Lattner7edc8c22005-04-07 17:14:51 +00001679 if (!Op0->getType()->isFloatingPoint())
1680 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1681 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001682 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1683 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1684 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1685 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001686 } else if (Op0I->getOpcode() == Instruction::Sub) {
1687 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1688 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001689 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001690
Chris Lattner50af16a2004-11-13 19:50:12 +00001691 ConstantInt *C1;
1692 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1693 if (X == Op1) { // X*C - X --> X * (C-1)
1694 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1695 return BinaryOperator::createMul(Op1, CP1);
1696 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001697
Chris Lattner50af16a2004-11-13 19:50:12 +00001698 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1699 if (X == dyn_castFoldableMul(Op1, C2))
1700 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1701 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001702 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001703}
1704
Chris Lattner4cb170c2004-02-23 06:38:22 +00001705/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1706/// really just returns true if the most significant (sign) bit is set.
1707static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1708 if (RHS->getType()->isSigned()) {
1709 // True if source is LHS < 0 or LHS <= -1
1710 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1711 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1712 } else {
1713 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1714 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1715 // the size of the integer type.
1716 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001717 return RHSC->getValue() ==
1718 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001719 if (Opcode == Instruction::SetGT)
1720 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001721 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001722 }
1723 return false;
1724}
1725
Chris Lattner7e708292002-06-25 16:13:24 +00001726Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001727 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001728 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001729
Chris Lattnere87597f2004-10-16 18:11:37 +00001730 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1731 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1732
Chris Lattner233f7dc2002-08-12 21:17:25 +00001733 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001734 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1735 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001736
1737 // ((X << C1)*C2) == (X * (C2 << C1))
1738 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1739 if (SI->getOpcode() == Instruction::Shl)
1740 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001741 return BinaryOperator::createMul(SI->getOperand(0),
1742 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001743
Chris Lattner515c97c2003-09-11 22:24:54 +00001744 if (CI->isNullValue())
1745 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1746 if (CI->equalsInt(1)) // X * 1 == X
1747 return ReplaceInstUsesWith(I, Op0);
1748 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001749 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001750
Chris Lattner515c97c2003-09-11 22:24:54 +00001751 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001752 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1753 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001754 return new ShiftInst(Instruction::Shl, Op0,
1755 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001756 }
Robert Bocchino71698282004-07-27 21:02:21 +00001757 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001758 if (Op1F->isNullValue())
1759 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001760
Chris Lattnera2881962003-02-18 19:28:33 +00001761 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1762 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1763 if (Op1F->getValue() == 1.0)
1764 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1765 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001766
1767 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1768 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1769 isa<ConstantInt>(Op0I->getOperand(1))) {
1770 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1771 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1772 Op1, "tmp");
1773 InsertNewInstBefore(Add, I);
1774 Value *C1C2 = ConstantExpr::getMul(Op1,
1775 cast<Constant>(Op0I->getOperand(1)));
1776 return BinaryOperator::createAdd(Add, C1C2);
1777
1778 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001779
1780 // Try to fold constant mul into select arguments.
1781 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001782 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001783 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001784
1785 if (isa<PHINode>(Op0))
1786 if (Instruction *NV = FoldOpIntoPhi(I))
1787 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001788 }
1789
Chris Lattnera4f445b2003-03-10 23:23:04 +00001790 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1791 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001792 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001793
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001794 // If one of the operands of the multiply is a cast from a boolean value, then
1795 // we know the bool is either zero or one, so this is a 'masking' multiply.
1796 // See if we can simplify things based on how the boolean was originally
1797 // formed.
1798 CastInst *BoolCast = 0;
1799 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1800 if (CI->getOperand(0)->getType() == Type::BoolTy)
1801 BoolCast = CI;
1802 if (!BoolCast)
1803 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1804 if (CI->getOperand(0)->getType() == Type::BoolTy)
1805 BoolCast = CI;
1806 if (BoolCast) {
1807 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1808 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1809 const Type *SCOpTy = SCIOp0->getType();
1810
Chris Lattner4cb170c2004-02-23 06:38:22 +00001811 // If the setcc is true iff the sign bit of X is set, then convert this
1812 // multiply into a shift/and combination.
1813 if (isa<ConstantInt>(SCIOp1) &&
1814 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001815 // Shift the X value right to turn it into "all signbits".
1816 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001817 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001818 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001819 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001820 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1821 SCIOp0->getName()), I);
1822 }
1823
1824 Value *V =
1825 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1826 BoolCast->getOperand(0)->getName()+
1827 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001828
1829 // If the multiply type is not the same as the source type, sign extend
1830 // or truncate to the multiply type.
1831 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001832 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001833
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001834 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001835 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001836 }
1837 }
1838 }
1839
Chris Lattner7e708292002-06-25 16:13:24 +00001840 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001841}
1842
Chris Lattner7e708292002-06-25 16:13:24 +00001843Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001844 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001845
Chris Lattner857e8cd2004-12-12 21:48:58 +00001846 if (isa<UndefValue>(Op0)) // undef / X -> 0
1847 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1848 if (isa<UndefValue>(Op1))
1849 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1850
1851 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001852 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001853 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001854 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001855
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001856 // div X, -1 == -X
1857 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001858 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001859
Chris Lattner857e8cd2004-12-12 21:48:58 +00001860 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001861 if (LHS->getOpcode() == Instruction::Div)
1862 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001863 // (X / C1) / C2 -> X / (C1*C2)
1864 return BinaryOperator::createDiv(LHS->getOperand(0),
1865 ConstantExpr::getMul(RHS, LHSRHS));
1866 }
1867
Chris Lattnera2881962003-02-18 19:28:33 +00001868 // Check to see if this is an unsigned division with an exact power of 2,
1869 // if so, convert to a right shift.
1870 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1871 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001872 if (isPowerOf2_64(Val)) {
1873 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001874 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001875 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001876 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001877
Chris Lattnera052f822004-10-09 02:50:40 +00001878 // -X/C -> X/-C
1879 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001880 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001881 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1882
Chris Lattner857e8cd2004-12-12 21:48:58 +00001883 if (!RHS->isNullValue()) {
1884 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001885 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001886 return R;
1887 if (isa<PHINode>(Op0))
1888 if (Instruction *NV = FoldOpIntoPhi(I))
1889 return NV;
1890 }
Chris Lattnera2881962003-02-18 19:28:33 +00001891 }
1892
Chris Lattner857e8cd2004-12-12 21:48:58 +00001893 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1894 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1896 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1897 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1898 if (STO->getValue() == 0) { // Couldn't be this argument.
1899 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001900 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001901 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001902 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001903 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001904 }
1905
Chris Lattnerbf70b832005-04-08 04:03:26 +00001906 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001907 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1908 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001909 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1910 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1911 TC, SI->getName()+".t");
1912 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001913
Chris Lattnerbf70b832005-04-08 04:03:26 +00001914 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1915 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1916 FC, SI->getName()+".f");
1917 FSI = InsertNewInstBefore(FSI, I);
1918 return new SelectInst(SI->getOperand(0), TSI, FSI);
1919 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001920 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001921
Chris Lattnera2881962003-02-18 19:28:33 +00001922 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001923 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001924 if (LHS->equalsInt(0))
1925 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1926
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001927 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00001928 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001929 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001930 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1931 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001932 const Type *NTy = Op0->getType()->getUnsignedVersion();
1933 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1934 InsertNewInstBefore(LHS, I);
1935 Value *RHS;
1936 if (Constant *R = dyn_cast<Constant>(Op1))
1937 RHS = ConstantExpr::getCast(R, NTy);
1938 else
1939 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1940 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1941 InsertNewInstBefore(Div, I);
1942 return new CastInst(Div, I.getType());
1943 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001944 } else {
1945 // Known to be an unsigned division.
1946 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1947 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1948 if (RHSI->getOpcode() == Instruction::Shl &&
1949 isa<ConstantUInt>(RHSI->getOperand(0))) {
1950 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1951 if (isPowerOf2_64(C1)) {
1952 unsigned C2 = Log2_64(C1);
1953 Value *Add = RHSI->getOperand(1);
1954 if (C2) {
1955 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1956 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1957 "tmp"), I);
1958 }
1959 return new ShiftInst(Instruction::Shr, Op0, Add);
1960 }
1961 }
1962 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001963 }
1964
Chris Lattner3f5b8772002-05-06 16:14:14 +00001965 return 0;
1966}
1967
1968
Chris Lattnerdb3f8732006-03-02 06:50:58 +00001969/// GetFactor - If we can prove that the specified value is at least a multiple
1970/// of some factor, return that factor.
1971static Constant *GetFactor(Value *V) {
1972 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1973 return CI;
1974
1975 // Unless we can be tricky, we know this is a multiple of 1.
1976 Constant *Result = ConstantInt::get(V->getType(), 1);
1977
1978 Instruction *I = dyn_cast<Instruction>(V);
1979 if (!I) return Result;
1980
1981 if (I->getOpcode() == Instruction::Mul) {
1982 // Handle multiplies by a constant, etc.
1983 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1984 GetFactor(I->getOperand(1)));
1985 } else if (I->getOpcode() == Instruction::Shl) {
1986 // (X<<C) -> X * (1 << C)
1987 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1988 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1989 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1990 }
1991 } else if (I->getOpcode() == Instruction::And) {
1992 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1993 // X & 0xFFF0 is known to be a multiple of 16.
1994 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1995 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1996 return ConstantExpr::getShl(Result,
1997 ConstantUInt::get(Type::UByteTy, Zeros));
1998 }
1999 } else if (I->getOpcode() == Instruction::Cast) {
2000 Value *Op = I->getOperand(0);
2001 // Only handle int->int casts.
2002 if (!Op->getType()->isInteger()) return Result;
2003 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2004 }
2005 return Result;
2006}
2007
Chris Lattner7e708292002-06-25 16:13:24 +00002008Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002009 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002010
2011 // 0 % X == 0, we don't need to preserve faults!
2012 if (Constant *LHS = dyn_cast<Constant>(Op0))
2013 if (LHS->isNullValue())
2014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2015
2016 if (isa<UndefValue>(Op0)) // undef % X -> 0
2017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2018 if (isa<UndefValue>(Op1))
2019 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2020
Chris Lattner11a49f22005-11-05 07:28:37 +00002021 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002022 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00002023 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00002024 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00002025 // X % -Y -> X % Y
2026 AddUsesToWorkList(I);
2027 I.setOperand(1, RHSNeg);
2028 return &I;
2029 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002030
2031 // If the top bits of both operands are zero (i.e. we can prove they are
2032 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002033 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2034 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00002035 const Type *NTy = Op0->getType()->getUnsignedVersion();
2036 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2037 InsertNewInstBefore(LHS, I);
2038 Value *RHS;
2039 if (Constant *R = dyn_cast<Constant>(Op1))
2040 RHS = ConstantExpr::getCast(R, NTy);
2041 else
2042 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2043 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2044 InsertNewInstBefore(Rem, I);
2045 return new CastInst(Rem, I.getType());
2046 }
2047 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002048
Chris Lattner857e8cd2004-12-12 21:48:58 +00002049 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002050 // X % 0 == undef, we don't need to preserve faults!
2051 if (RHS->equalsInt(0))
2052 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2053
Chris Lattnera2881962003-02-18 19:28:33 +00002054 if (RHS->equalsInt(1)) // X % 1 == 0
2055 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2056
2057 // Check to see if this is an unsigned remainder with an exact power of 2,
2058 // if so, convert to a bitwise and.
2059 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002060 if (isPowerOf2_64(C->getValue()))
2061 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattner857e8cd2004-12-12 21:48:58 +00002062
Chris Lattner97943922006-02-28 05:49:21 +00002063 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2064 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2065 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2066 return R;
2067 } else if (isa<PHINode>(Op0I)) {
2068 if (Instruction *NV = FoldOpIntoPhi(I))
2069 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002070 }
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002071
2072 // X*C1%C2 --> 0 iff C1%C2 == 0
2073 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2074 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002075 }
Chris Lattnera2881962003-02-18 19:28:33 +00002076 }
2077
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002078 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2079 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2080 if (I.getType()->isUnsigned() &&
2081 RHSI->getOpcode() == Instruction::Shl &&
2082 isa<ConstantUInt>(RHSI->getOperand(0))) {
2083 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2084 if (isPowerOf2_64(C1)) {
2085 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2086 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2087 "tmp"), I);
2088 return BinaryOperator::createAnd(Op0, Add);
2089 }
2090 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002091
2092 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2093 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2094 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2095 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2096 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2097 if (STO->getValue() == 0) { // Couldn't be this argument.
2098 I.setOperand(1, SFO);
2099 return &I;
2100 } else if (SFO->getValue() == 0) {
2101 I.setOperand(1, STO);
2102 return &I;
2103 }
2104
2105 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2106 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2107 SubOne(STO), SI->getName()+".t"), I);
2108 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2109 SubOne(SFO), SI->getName()+".f"), I);
2110 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2111 }
2112 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002113 }
2114
Chris Lattner3f5b8772002-05-06 16:14:14 +00002115 return 0;
2116}
2117
Chris Lattner8b170942002-08-09 23:47:40 +00002118// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002119static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner1a074fc2006-02-07 07:00:41 +00002120 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2121 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002122
2123 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00002124
Chris Lattner8b170942002-08-09 23:47:40 +00002125 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00002126 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002127 int64_t Val = INT64_MAX; // All ones
2128 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2129 return CS->getValue() == Val-1;
2130}
2131
2132// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002133static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00002134 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2135 return CU->getValue() == 1;
2136
2137 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00002138
2139 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00002140 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002141 int64_t Val = -1; // All ones
2142 Val <<= TypeBits-1; // Shift over to the right spot
2143 return CS->getValue() == Val+1;
2144}
2145
Chris Lattner457dd822004-06-09 07:59:58 +00002146// isOneBitSet - Return true if there is exactly one bit set in the specified
2147// constant.
2148static bool isOneBitSet(const ConstantInt *CI) {
2149 uint64_t V = CI->getRawValue();
2150 return V && (V & (V-1)) == 0;
2151}
2152
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002153#if 0 // Currently unused
2154// isLowOnes - Return true if the constant is of the form 0+1+.
2155static bool isLowOnes(const ConstantInt *CI) {
2156 uint64_t V = CI->getRawValue();
2157
2158 // There won't be bits set in parts that the type doesn't contain.
2159 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2160
2161 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2162 return U && V && (U & V) == 0;
2163}
2164#endif
2165
2166// isHighOnes - Return true if the constant is of the form 1+0+.
2167// This is the same as lowones(~X).
2168static bool isHighOnes(const ConstantInt *CI) {
2169 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002170 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002171
2172 // There won't be bits set in parts that the type doesn't contain.
2173 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2174
2175 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2176 return U && V && (U & V) == 0;
2177}
2178
2179
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002180/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2181/// are carefully arranged to allow folding of expressions such as:
2182///
2183/// (A < B) | (A > B) --> (A != B)
2184///
2185/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2186/// represents that the comparison is true if A == B, and bit value '1' is true
2187/// if A < B.
2188///
2189static unsigned getSetCondCode(const SetCondInst *SCI) {
2190 switch (SCI->getOpcode()) {
2191 // False -> 0
2192 case Instruction::SetGT: return 1;
2193 case Instruction::SetEQ: return 2;
2194 case Instruction::SetGE: return 3;
2195 case Instruction::SetLT: return 4;
2196 case Instruction::SetNE: return 5;
2197 case Instruction::SetLE: return 6;
2198 // True -> 7
2199 default:
2200 assert(0 && "Invalid SetCC opcode!");
2201 return 0;
2202 }
2203}
2204
2205/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2206/// opcode and two operands into either a constant true or false, or a brand new
2207/// SetCC instruction.
2208static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2209 switch (Opcode) {
2210 case 0: return ConstantBool::False;
2211 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2212 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2213 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2214 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2215 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2216 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2217 case 7: return ConstantBool::True;
2218 default: assert(0 && "Illegal SetCCCode!"); return 0;
2219 }
2220}
2221
2222// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2223struct FoldSetCCLogical {
2224 InstCombiner &IC;
2225 Value *LHS, *RHS;
2226 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2227 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2228 bool shouldApply(Value *V) const {
2229 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2230 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2231 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2232 return false;
2233 }
2234 Instruction *apply(BinaryOperator &Log) const {
2235 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2236 if (SCI->getOperand(0) != LHS) {
2237 assert(SCI->getOperand(1) == LHS);
2238 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2239 }
2240
2241 unsigned LHSCode = getSetCondCode(SCI);
2242 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2243 unsigned Code;
2244 switch (Log.getOpcode()) {
2245 case Instruction::And: Code = LHSCode & RHSCode; break;
2246 case Instruction::Or: Code = LHSCode | RHSCode; break;
2247 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002248 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002249 }
2250
2251 Value *RV = getSetCCValue(Code, LHS, RHS);
2252 if (Instruction *I = dyn_cast<Instruction>(RV))
2253 return I;
2254 // Otherwise, it's a constant boolean value...
2255 return IC.ReplaceInstUsesWith(Log, RV);
2256 }
2257};
2258
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002259// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2260// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2261// guaranteed to be either a shift instruction or a binary operator.
2262Instruction *InstCombiner::OptAndOp(Instruction *Op,
2263 ConstantIntegral *OpRHS,
2264 ConstantIntegral *AndRHS,
2265 BinaryOperator &TheAnd) {
2266 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002267 Constant *Together = 0;
2268 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002269 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002270
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002271 switch (Op->getOpcode()) {
2272 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002273 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002274 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2275 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002276 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002277 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002278 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002279 }
2280 break;
2281 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002282 if (Together == AndRHS) // (X | C) & C --> C
2283 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002284
Chris Lattner6e7ba452005-01-01 16:22:27 +00002285 if (Op->hasOneUse() && Together != OpRHS) {
2286 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2287 std::string Op0Name = Op->getName(); Op->setName("");
2288 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2289 InsertNewInstBefore(Or, TheAnd);
2290 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002291 }
2292 break;
2293 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002294 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002295 // Adding a one to a single bit bit-field should be turned into an XOR
2296 // of the bit. First thing to check is to see if this AND is with a
2297 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00002298 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002299
2300 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002301 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002302
2303 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002304 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002305 // Ok, at this point, we know that we are masking the result of the
2306 // ADD down to exactly one bit. If the constant we are adding has
2307 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00002308 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002309
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002310 // Check to see if any bits below the one bit set in AndRHSV are set.
2311 if ((AddRHS & (AndRHSV-1)) == 0) {
2312 // If not, the only thing that can effect the output of the AND is
2313 // the bit specified by AndRHSV. If that bit is set, the effect of
2314 // the XOR is to toggle the bit. If it is clear, then the ADD has
2315 // no effect.
2316 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2317 TheAnd.setOperand(0, X);
2318 return &TheAnd;
2319 } else {
2320 std::string Name = Op->getName(); Op->setName("");
2321 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002322 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002323 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002324 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002325 }
2326 }
2327 }
2328 }
2329 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002330
2331 case Instruction::Shl: {
2332 // We know that the AND will not produce any of the bits shifted in, so if
2333 // the anded constant includes them, clear them now!
2334 //
2335 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002336 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2337 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002338
Chris Lattner0c967662004-09-24 15:21:34 +00002339 if (CI == ShlMask) { // Masking out bits that the shift already masks
2340 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2341 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002342 TheAnd.setOperand(1, CI);
2343 return &TheAnd;
2344 }
2345 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002346 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002347 case Instruction::Shr:
2348 // We know that the AND will not produce any of the bits shifted in, so if
2349 // the anded constant includes them, clear them now! This only applies to
2350 // unsigned shifts, because a signed shr may bring in set bits!
2351 //
2352 if (AndRHS->getType()->isUnsigned()) {
2353 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002354 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2355 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2356
2357 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2358 return ReplaceInstUsesWith(TheAnd, Op);
2359 } else if (CI != AndRHS) {
2360 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00002361 return &TheAnd;
2362 }
Chris Lattner0c967662004-09-24 15:21:34 +00002363 } else { // Signed shr.
2364 // See if this is shifting in some sign extension, then masking it out
2365 // with an and.
2366 if (Op->hasOneUse()) {
2367 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2368 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2369 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00002370 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00002371 // Make the argument unsigned.
2372 Value *ShVal = Op->getOperand(0);
2373 ShVal = InsertCastBefore(ShVal,
2374 ShVal->getType()->getUnsignedVersion(),
2375 TheAnd);
2376 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2377 OpRHS, Op->getName()),
2378 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00002379 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2380 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2381 TheAnd.getName()),
2382 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00002383 return new CastInst(ShVal, Op->getType());
2384 }
2385 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002386 }
2387 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002388 }
2389 return 0;
2390}
2391
Chris Lattner8b170942002-08-09 23:47:40 +00002392
Chris Lattnera96879a2004-09-29 17:40:11 +00002393/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2394/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2395/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2396/// insert new instructions.
2397Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2398 bool Inside, Instruction &IB) {
2399 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2400 "Lo is not <= Hi in range emission code!");
2401 if (Inside) {
2402 if (Lo == Hi) // Trivially false.
2403 return new SetCondInst(Instruction::SetNE, V, V);
2404 if (cast<ConstantIntegral>(Lo)->isMinValue())
2405 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002406
Chris Lattnera96879a2004-09-29 17:40:11 +00002407 Constant *AddCST = ConstantExpr::getNeg(Lo);
2408 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2409 InsertNewInstBefore(Add, IB);
2410 // Convert to unsigned for the comparison.
2411 const Type *UnsType = Add->getType()->getUnsignedVersion();
2412 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2413 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2414 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2415 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2416 }
2417
2418 if (Lo == Hi) // Trivially true.
2419 return new SetCondInst(Instruction::SetEQ, V, V);
2420
2421 Hi = SubOne(cast<ConstantInt>(Hi));
2422 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2423 return new SetCondInst(Instruction::SetGT, V, Hi);
2424
2425 // Emit X-Lo > Hi-Lo-1
2426 Constant *AddCST = ConstantExpr::getNeg(Lo);
2427 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2428 InsertNewInstBefore(Add, IB);
2429 // Convert to unsigned for the comparison.
2430 const Type *UnsType = Add->getType()->getUnsignedVersion();
2431 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2432 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2433 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2434 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2435}
2436
Chris Lattner7203e152005-09-18 07:22:02 +00002437// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2438// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2439// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2440// not, since all 1s are not contiguous.
2441static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2442 uint64_t V = Val->getRawValue();
2443 if (!isShiftedMask_64(V)) return false;
2444
2445 // look for the first zero bit after the run of ones
2446 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2447 // look for the first non-zero bit
2448 ME = 64-CountLeadingZeros_64(V);
2449 return true;
2450}
2451
2452
2453
2454/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2455/// where isSub determines whether the operator is a sub. If we can fold one of
2456/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002457///
2458/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2459/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2460/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2461///
2462/// return (A +/- B).
2463///
2464Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2465 ConstantIntegral *Mask, bool isSub,
2466 Instruction &I) {
2467 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2468 if (!LHSI || LHSI->getNumOperands() != 2 ||
2469 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2470
2471 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2472
2473 switch (LHSI->getOpcode()) {
2474 default: return 0;
2475 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002476 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2477 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2478 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2479 break;
2480
2481 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2482 // part, we don't need any explicit masks to take them out of A. If that
2483 // is all N is, ignore it.
2484 unsigned MB, ME;
2485 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002486 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2487 Mask >>= 64-MB+1;
2488 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002489 break;
2490 }
2491 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002492 return 0;
2493 case Instruction::Or:
2494 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002495 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2496 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2497 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002498 break;
2499 return 0;
2500 }
2501
2502 Instruction *New;
2503 if (isSub)
2504 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2505 else
2506 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2507 return InsertNewInstBefore(New, I);
2508}
2509
Chris Lattner7e708292002-06-25 16:13:24 +00002510Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002511 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002512 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002513
Chris Lattnere87597f2004-10-16 18:11:37 +00002514 if (isa<UndefValue>(Op1)) // X & undef -> 0
2515 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2516
Chris Lattner6e7ba452005-01-01 16:22:27 +00002517 // and X, X = X
2518 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002519 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002520
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002521 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002522 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00002523 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002524 if (!isa<PackedType>(I.getType()) &&
2525 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00002526 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00002527 return &I;
2528
Chris Lattner6e7ba452005-01-01 16:22:27 +00002529 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00002530 uint64_t AndRHSMask = AndRHS->getZExtValue();
2531 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00002532 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002533
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002534 // Optimize a variety of ((val OP C1) & C2) combinations...
2535 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2536 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002537 Value *Op0LHS = Op0I->getOperand(0);
2538 Value *Op0RHS = Op0I->getOperand(1);
2539 switch (Op0I->getOpcode()) {
2540 case Instruction::Xor:
2541 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002542 // If the mask is only needed on one incoming arm, push it up.
2543 if (Op0I->hasOneUse()) {
2544 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2545 // Not masking anything out for the LHS, move to RHS.
2546 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2547 Op0RHS->getName()+".masked");
2548 InsertNewInstBefore(NewRHS, I);
2549 return BinaryOperator::create(
2550 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002551 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00002552 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00002553 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2554 // Not masking anything out for the RHS, move to LHS.
2555 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2556 Op0LHS->getName()+".masked");
2557 InsertNewInstBefore(NewLHS, I);
2558 return BinaryOperator::create(
2559 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2560 }
2561 }
2562
Chris Lattner6e7ba452005-01-01 16:22:27 +00002563 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002564 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002565 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2566 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2567 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2568 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2569 return BinaryOperator::createAnd(V, AndRHS);
2570 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2571 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002572 break;
2573
2574 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002575 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2576 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2577 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2578 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2579 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002580 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002581 }
2582
Chris Lattner58403262003-07-23 19:25:52 +00002583 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002584 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002585 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002586 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2587 const Type *SrcTy = CI->getOperand(0)->getType();
2588
Chris Lattner2b83af22005-08-07 07:03:10 +00002589 // If this is an integer truncation or change from signed-to-unsigned, and
2590 // if the source is an and/or with immediate, transform it. This
2591 // frequently occurs for bitfield accesses.
2592 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2593 if (SrcTy->getPrimitiveSizeInBits() >=
2594 I.getType()->getPrimitiveSizeInBits() &&
2595 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00002596 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00002597 if (CastOp->getOpcode() == Instruction::And) {
2598 // Change: and (cast (and X, C1) to T), C2
2599 // into : and (cast X to T), trunc(C1)&C2
2600 // This will folds the two ands together, which may allow other
2601 // simplifications.
2602 Instruction *NewCast =
2603 new CastInst(CastOp->getOperand(0), I.getType(),
2604 CastOp->getName()+".shrunk");
2605 NewCast = InsertNewInstBefore(NewCast, I);
2606
2607 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2608 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2609 return BinaryOperator::createAnd(NewCast, C3);
2610 } else if (CastOp->getOpcode() == Instruction::Or) {
2611 // Change: and (cast (or X, C1) to T), C2
2612 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2613 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2614 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2615 return ReplaceInstUsesWith(I, AndRHS);
2616 }
2617 }
Chris Lattner06782f82003-07-23 19:36:21 +00002618 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002619
2620 // Try to fold constant and into select arguments.
2621 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002622 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002623 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002624 if (isa<PHINode>(Op0))
2625 if (Instruction *NV = FoldOpIntoPhi(I))
2626 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002627 }
2628
Chris Lattner8d969642003-03-10 23:06:50 +00002629 Value *Op0NotVal = dyn_castNotVal(Op0);
2630 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002631
Chris Lattner5b62aa72004-06-18 06:07:51 +00002632 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2634
Misha Brukmancb6267b2004-07-30 12:50:08 +00002635 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00002636 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00002637 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2638 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002639 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00002640 return BinaryOperator::createNot(Or);
2641 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002642
2643 {
2644 Value *A = 0, *B = 0;
2645 ConstantInt *C1 = 0, *C2 = 0;
2646 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2647 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2648 return ReplaceInstUsesWith(I, Op1);
2649 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2650 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2651 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00002652
2653 if (Op0->hasOneUse() &&
2654 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2655 if (A == Op1) { // (A^B)&A -> A&(A^B)
2656 I.swapOperands(); // Simplify below
2657 std::swap(Op0, Op1);
2658 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2659 cast<BinaryOperator>(Op0)->swapOperands();
2660 I.swapOperands(); // Simplify below
2661 std::swap(Op0, Op1);
2662 }
2663 }
2664 if (Op1->hasOneUse() &&
2665 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2666 if (B == Op0) { // B&(A^B) -> B&(B^A)
2667 cast<BinaryOperator>(Op1)->swapOperands();
2668 std::swap(A, B);
2669 }
2670 if (A == Op0) { // A&(A^B) -> A & ~B
2671 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2672 InsertNewInstBefore(NotB, I);
2673 return BinaryOperator::createAnd(A, NotB);
2674 }
2675 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002676 }
2677
Chris Lattnera2881962003-02-18 19:28:33 +00002678
Chris Lattner955f3312004-09-28 21:48:02 +00002679 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2680 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002681 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2682 return R;
2683
Chris Lattner955f3312004-09-28 21:48:02 +00002684 Value *LHSVal, *RHSVal;
2685 ConstantInt *LHSCst, *RHSCst;
2686 Instruction::BinaryOps LHSCC, RHSCC;
2687 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2688 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2689 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2690 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002691 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00002692 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2693 // Ensure that the larger constant is on the RHS.
2694 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2695 SetCondInst *LHS = cast<SetCondInst>(Op0);
2696 if (cast<ConstantBool>(Cmp)->getValue()) {
2697 std::swap(LHS, RHS);
2698 std::swap(LHSCst, RHSCst);
2699 std::swap(LHSCC, RHSCC);
2700 }
2701
2702 // At this point, we know we have have two setcc instructions
2703 // comparing a value against two constants and and'ing the result
2704 // together. Because of the above check, we know that we only have
2705 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2706 // FoldSetCCLogical check above), that the two constants are not
2707 // equal.
2708 assert(LHSCst != RHSCst && "Compares not folded above?");
2709
2710 switch (LHSCC) {
2711 default: assert(0 && "Unknown integer condition code!");
2712 case Instruction::SetEQ:
2713 switch (RHSCC) {
2714 default: assert(0 && "Unknown integer condition code!");
2715 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2716 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2717 return ReplaceInstUsesWith(I, ConstantBool::False);
2718 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2719 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2720 return ReplaceInstUsesWith(I, LHS);
2721 }
2722 case Instruction::SetNE:
2723 switch (RHSCC) {
2724 default: assert(0 && "Unknown integer condition code!");
2725 case Instruction::SetLT:
2726 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2727 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2728 break; // (X != 13 & X < 15) -> no change
2729 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2730 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2731 return ReplaceInstUsesWith(I, RHS);
2732 case Instruction::SetNE:
2733 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2734 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2735 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2736 LHSVal->getName()+".off");
2737 InsertNewInstBefore(Add, I);
2738 const Type *UnsType = Add->getType()->getUnsignedVersion();
2739 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2740 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2741 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2742 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2743 }
2744 break; // (X != 13 & X != 15) -> no change
2745 }
2746 break;
2747 case Instruction::SetLT:
2748 switch (RHSCC) {
2749 default: assert(0 && "Unknown integer condition code!");
2750 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2751 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2752 return ReplaceInstUsesWith(I, ConstantBool::False);
2753 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2754 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2755 return ReplaceInstUsesWith(I, LHS);
2756 }
2757 case Instruction::SetGT:
2758 switch (RHSCC) {
2759 default: assert(0 && "Unknown integer condition code!");
2760 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2761 return ReplaceInstUsesWith(I, LHS);
2762 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2763 return ReplaceInstUsesWith(I, RHS);
2764 case Instruction::SetNE:
2765 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2766 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2767 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002768 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2769 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002770 }
2771 }
2772 }
2773 }
2774
Chris Lattner6fc205f2006-05-05 06:39:07 +00002775 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2776 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00002777 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00002778 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00002779 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00002780 // Only do this if the casts both really cause code to be generated.
2781 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2782 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002783 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2784 Op1C->getOperand(0),
2785 I.getName());
2786 InsertNewInstBefore(NewOp, I);
2787 return new CastInst(NewOp, I.getType());
2788 }
2789 }
2790
Chris Lattner7e708292002-06-25 16:13:24 +00002791 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002792}
2793
Chris Lattner7e708292002-06-25 16:13:24 +00002794Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002795 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002796 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002797
Chris Lattnere87597f2004-10-16 18:11:37 +00002798 if (isa<UndefValue>(Op1))
2799 return ReplaceInstUsesWith(I, // X | undef -> -1
2800 ConstantIntegral::getAllOnesValue(I.getType()));
2801
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002802 // or X, X = X
2803 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002804 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002805
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002806 // See if we can simplify any instructions used by the instruction whose sole
2807 // purpose is to compute bits we don't care about.
2808 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002809 if (!isa<PackedType>(I.getType()) &&
2810 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002811 KnownZero, KnownOne))
2812 return &I;
2813
Chris Lattner3f5b8772002-05-06 16:14:14 +00002814 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002815 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002816 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002817 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2818 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002819 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2820 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002821 InsertNewInstBefore(Or, I);
2822 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2823 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002824
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002825 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2826 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2827 std::string Op0Name = Op0->getName(); Op0->setName("");
2828 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2829 InsertNewInstBefore(Or, I);
2830 return BinaryOperator::createXor(Or,
2831 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002832 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002833
2834 // Try to fold constant and into select arguments.
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002836 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002837 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002838 if (isa<PHINode>(Op0))
2839 if (Instruction *NV = FoldOpIntoPhi(I))
2840 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002841 }
2842
Chris Lattner4f637d42006-01-06 17:59:59 +00002843 Value *A = 0, *B = 0;
2844 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002845
2846 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2847 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2848 return ReplaceInstUsesWith(I, Op1);
2849 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2850 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2851 return ReplaceInstUsesWith(I, Op0);
2852
Chris Lattner6e4c6492005-05-09 04:58:36 +00002853 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2854 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002855 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002856 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2857 Op0->setName("");
2858 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2859 }
2860
2861 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2862 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002863 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002864 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2865 Op0->setName("");
2866 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2867 }
2868
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002869 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002870 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002871 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2872
2873 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2874 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2875
2876
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002877 // If we have: ((V + N) & C1) | (V & C2)
2878 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2879 // replace with V+N.
2880 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002881 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002882 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2883 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2884 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002885 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002886 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002887 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002888 return ReplaceInstUsesWith(I, A);
2889 }
2890 // Or commutes, try both ways.
2891 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2892 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2893 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002894 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002895 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002896 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002897 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002898 }
2899 }
2900 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002901
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002902 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2903 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002904 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002905 ConstantIntegral::getAllOnesValue(I.getType()));
2906 } else {
2907 A = 0;
2908 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002909 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002910 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2911 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002912 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002913 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002914
Misha Brukmancb6267b2004-07-30 12:50:08 +00002915 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002916 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2917 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2918 I.getName()+".demorgan"), I);
2919 return BinaryOperator::createNot(And);
2920 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002921 }
Chris Lattnera2881962003-02-18 19:28:33 +00002922
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002923 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002924 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002925 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2926 return R;
2927
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002928 Value *LHSVal, *RHSVal;
2929 ConstantInt *LHSCst, *RHSCst;
2930 Instruction::BinaryOps LHSCC, RHSCC;
2931 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2932 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2933 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2934 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002935 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002936 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2937 // Ensure that the larger constant is on the RHS.
2938 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2939 SetCondInst *LHS = cast<SetCondInst>(Op0);
2940 if (cast<ConstantBool>(Cmp)->getValue()) {
2941 std::swap(LHS, RHS);
2942 std::swap(LHSCst, RHSCst);
2943 std::swap(LHSCC, RHSCC);
2944 }
2945
2946 // At this point, we know we have have two setcc instructions
2947 // comparing a value against two constants and or'ing the result
2948 // together. Because of the above check, we know that we only have
2949 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2950 // FoldSetCCLogical check above), that the two constants are not
2951 // equal.
2952 assert(LHSCst != RHSCst && "Compares not folded above?");
2953
2954 switch (LHSCC) {
2955 default: assert(0 && "Unknown integer condition code!");
2956 case Instruction::SetEQ:
2957 switch (RHSCC) {
2958 default: assert(0 && "Unknown integer condition code!");
2959 case Instruction::SetEQ:
2960 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2961 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2962 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2963 LHSVal->getName()+".off");
2964 InsertNewInstBefore(Add, I);
2965 const Type *UnsType = Add->getType()->getUnsignedVersion();
2966 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2967 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2968 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2969 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2970 }
2971 break; // (X == 13 | X == 15) -> no change
2972
Chris Lattner240d6f42005-04-19 06:04:18 +00002973 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2974 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002975 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2976 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2977 return ReplaceInstUsesWith(I, RHS);
2978 }
2979 break;
2980 case Instruction::SetNE:
2981 switch (RHSCC) {
2982 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002983 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2984 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2985 return ReplaceInstUsesWith(I, LHS);
2986 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002987 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002988 return ReplaceInstUsesWith(I, ConstantBool::True);
2989 }
2990 break;
2991 case Instruction::SetLT:
2992 switch (RHSCC) {
2993 default: assert(0 && "Unknown integer condition code!");
2994 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2995 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002996 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2997 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002998 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2999 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3000 return ReplaceInstUsesWith(I, RHS);
3001 }
3002 break;
3003 case Instruction::SetGT:
3004 switch (RHSCC) {
3005 default: assert(0 && "Unknown integer condition code!");
3006 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3007 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3008 return ReplaceInstUsesWith(I, LHS);
3009 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3010 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3011 return ReplaceInstUsesWith(I, ConstantBool::True);
3012 }
3013 }
3014 }
3015 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003016
3017 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3018 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003019 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003020 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003021 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003022 // Only do this if the casts both really cause code to be generated.
3023 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3024 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003025 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3026 Op1C->getOperand(0),
3027 I.getName());
3028 InsertNewInstBefore(NewOp, I);
3029 return new CastInst(NewOp, I.getType());
3030 }
3031 }
3032
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003033
Chris Lattner7e708292002-06-25 16:13:24 +00003034 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003035}
3036
Chris Lattnerc317d392004-02-16 01:20:27 +00003037// XorSelf - Implements: X ^ X --> 0
3038struct XorSelf {
3039 Value *RHS;
3040 XorSelf(Value *rhs) : RHS(rhs) {}
3041 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3042 Instruction *apply(BinaryOperator &Xor) const {
3043 return &Xor;
3044 }
3045};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003046
3047
Chris Lattner7e708292002-06-25 16:13:24 +00003048Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003049 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003050 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003051
Chris Lattnere87597f2004-10-16 18:11:37 +00003052 if (isa<UndefValue>(Op1))
3053 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3054
Chris Lattnerc317d392004-02-16 01:20:27 +00003055 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3056 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3057 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003058 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003059 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003060
3061 // See if we can simplify any instructions used by the instruction whose sole
3062 // purpose is to compute bits we don't care about.
3063 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003064 if (!isa<PackedType>(I.getType()) &&
3065 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003066 KnownZero, KnownOne))
3067 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003068
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003069 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003070 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00003071 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003072 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00003073 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00003074 return new SetCondInst(SCI->getInverseCondition(),
3075 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003076
Chris Lattnerd65460f2003-11-05 01:06:05 +00003077 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003078 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3079 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003080 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3081 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003082 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003083 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003084 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003085
3086 // ~(~X & Y) --> (X | ~Y)
3087 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3088 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3089 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3090 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003091 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003092 Op0I->getOperand(1)->getName()+".not");
3093 InsertNewInstBefore(NotY, I);
3094 return BinaryOperator::createOr(Op0NotVal, NotY);
3095 }
3096 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003097
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003098 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003099 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003100 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003101 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003102 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3103 return BinaryOperator::createSub(
3104 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003105 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003106 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003107 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003108 } else if (Op0I->getOpcode() == Instruction::Or) {
3109 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3110 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3111 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3112 // Anything in both C1 and C2 is known to be zero, remove it from
3113 // NewRHS.
3114 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3115 NewRHS = ConstantExpr::getAnd(NewRHS,
3116 ConstantExpr::getNot(CommonBits));
3117 WorkList.push_back(Op0I);
3118 I.setOperand(0, Op0I->getOperand(0));
3119 I.setOperand(1, NewRHS);
3120 return &I;
3121 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003122 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003123 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003124
3125 // Try to fold constant and into select arguments.
3126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003128 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003129 if (isa<PHINode>(Op0))
3130 if (Instruction *NV = FoldOpIntoPhi(I))
3131 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003132 }
3133
Chris Lattner8d969642003-03-10 23:06:50 +00003134 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003135 if (X == Op1)
3136 return ReplaceInstUsesWith(I,
3137 ConstantIntegral::getAllOnesValue(I.getType()));
3138
Chris Lattner8d969642003-03-10 23:06:50 +00003139 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003140 if (X == Op0)
3141 return ReplaceInstUsesWith(I,
3142 ConstantIntegral::getAllOnesValue(I.getType()));
3143
Chris Lattner64daab52006-04-01 08:03:55 +00003144 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00003145 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003146 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003147 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003148 I.swapOperands();
3149 std::swap(Op0, Op1);
3150 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003151 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003152 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003153 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003154 } else if (Op1I->getOpcode() == Instruction::Xor) {
3155 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3156 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3157 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3158 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003159 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3160 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3161 Op1I->swapOperands();
3162 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3163 I.swapOperands(); // Simplified below.
3164 std::swap(Op0, Op1);
3165 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003166 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003167
Chris Lattner64daab52006-04-01 08:03:55 +00003168 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00003169 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003170 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003171 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00003172 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00003173 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3174 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003175 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003176 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003177 } else if (Op0I->getOpcode() == Instruction::Xor) {
3178 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3179 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3180 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3181 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003182 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3183 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3184 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003185 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3186 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003187 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3188 InsertNewInstBefore(N, I);
3189 return BinaryOperator::createAnd(N, Op1);
3190 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003191 }
3192
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003193 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3194 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3195 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3196 return R;
3197
Chris Lattner6fc205f2006-05-05 06:39:07 +00003198 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3199 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003200 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003201 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003202 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003203 // Only do this if the casts both really cause code to be generated.
3204 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3205 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003206 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3207 Op1C->getOperand(0),
3208 I.getName());
3209 InsertNewInstBefore(NewOp, I);
3210 return new CastInst(NewOp, I.getType());
3211 }
3212 }
3213
Chris Lattner7e708292002-06-25 16:13:24 +00003214 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003215}
3216
Chris Lattnera96879a2004-09-29 17:40:11 +00003217/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3218/// overflowed for this type.
3219static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3220 ConstantInt *In2) {
3221 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3222 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3223}
3224
3225static bool isPositive(ConstantInt *C) {
3226 return cast<ConstantSInt>(C)->getValue() >= 0;
3227}
3228
3229/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3230/// overflowed for this type.
3231static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3232 ConstantInt *In2) {
3233 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3234
3235 if (In1->getType()->isUnsigned())
3236 return cast<ConstantUInt>(Result)->getValue() <
3237 cast<ConstantUInt>(In1)->getValue();
3238 if (isPositive(In1) != isPositive(In2))
3239 return false;
3240 if (isPositive(In1))
3241 return cast<ConstantSInt>(Result)->getValue() <
3242 cast<ConstantSInt>(In1)->getValue();
3243 return cast<ConstantSInt>(Result)->getValue() >
3244 cast<ConstantSInt>(In1)->getValue();
3245}
3246
Chris Lattner574da9b2005-01-13 20:14:25 +00003247/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3248/// code necessary to compute the offset from the base pointer (without adding
3249/// in the base pointer). Return the result as a signed integer of intptr size.
3250static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3251 TargetData &TD = IC.getTargetData();
3252 gep_type_iterator GTI = gep_type_begin(GEP);
3253 const Type *UIntPtrTy = TD.getIntPtrType();
3254 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3255 Value *Result = Constant::getNullValue(SIntPtrTy);
3256
3257 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003258 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003259
Chris Lattner574da9b2005-01-13 20:14:25 +00003260 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3261 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003262 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00003263 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3264 SIntPtrTy);
3265 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3266 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003267 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003268 Scale = ConstantExpr::getMul(OpC, Scale);
3269 if (Constant *RC = dyn_cast<Constant>(Result))
3270 Result = ConstantExpr::getAdd(RC, Scale);
3271 else {
3272 // Emit an add instruction.
3273 Result = IC.InsertNewInstBefore(
3274 BinaryOperator::createAdd(Result, Scale,
3275 GEP->getName()+".offs"), I);
3276 }
3277 }
3278 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003279 // Convert to correct type.
3280 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3281 Op->getName()+".c"), I);
3282 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003283 // We'll let instcombine(mul) convert this to a shl if possible.
3284 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3285 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003286
3287 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003288 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003289 GEP->getName()+".offs"), I);
3290 }
3291 }
3292 return Result;
3293}
3294
3295/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3296/// else. At this point we know that the GEP is on the LHS of the comparison.
3297Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3298 Instruction::BinaryOps Cond,
3299 Instruction &I) {
3300 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003301
3302 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3303 if (isa<PointerType>(CI->getOperand(0)->getType()))
3304 RHS = CI->getOperand(0);
3305
Chris Lattner574da9b2005-01-13 20:14:25 +00003306 Value *PtrBase = GEPLHS->getOperand(0);
3307 if (PtrBase == RHS) {
3308 // As an optimization, we don't actually have to compute the actual value of
3309 // OFFSET if this is a seteq or setne comparison, just return whether each
3310 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003311 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3312 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003313 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3314 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003315 bool EmitIt = true;
3316 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3317 if (isa<UndefValue>(C)) // undef index -> undef.
3318 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3319 if (C->isNullValue())
3320 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003321 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3322 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003323 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003324 return ReplaceInstUsesWith(I, // No comparison is needed here.
3325 ConstantBool::get(Cond == Instruction::SetNE));
3326 }
3327
3328 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003329 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003330 new SetCondInst(Cond, GEPLHS->getOperand(i),
3331 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3332 if (InVal == 0)
3333 InVal = Comp;
3334 else {
3335 InVal = InsertNewInstBefore(InVal, I);
3336 InsertNewInstBefore(Comp, I);
3337 if (Cond == Instruction::SetNE) // True if any are unequal
3338 InVal = BinaryOperator::createOr(InVal, Comp);
3339 else // True if all are equal
3340 InVal = BinaryOperator::createAnd(InVal, Comp);
3341 }
3342 }
3343 }
3344
3345 if (InVal)
3346 return InVal;
3347 else
3348 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3349 ConstantBool::get(Cond == Instruction::SetEQ));
3350 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003351
3352 // Only lower this if the setcc is the only user of the GEP or if we expect
3353 // the result to fold to a constant!
3354 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3355 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3356 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3357 return new SetCondInst(Cond, Offset,
3358 Constant::getNullValue(Offset->getType()));
3359 }
3360 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00003361 // If the base pointers are different, but the indices are the same, just
3362 // compare the base pointer.
3363 if (PtrBase != GEPRHS->getOperand(0)) {
3364 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00003365 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00003366 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00003367 if (IndicesTheSame)
3368 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3369 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3370 IndicesTheSame = false;
3371 break;
3372 }
3373
3374 // If all indices are the same, just compare the base pointers.
3375 if (IndicesTheSame)
3376 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3377 GEPRHS->getOperand(0));
3378
3379 // Otherwise, the base pointers are different and the indices are
3380 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00003381 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00003382 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003383
Chris Lattnere9d782b2005-01-13 22:25:21 +00003384 // If one of the GEPs has all zero indices, recurse.
3385 bool AllZeros = true;
3386 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3387 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3388 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3389 AllZeros = false;
3390 break;
3391 }
3392 if (AllZeros)
3393 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3394 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003395
3396 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003397 AllZeros = true;
3398 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3399 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3400 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3401 AllZeros = false;
3402 break;
3403 }
3404 if (AllZeros)
3405 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3406
Chris Lattner4401c9c2005-01-14 00:20:05 +00003407 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3408 // If the GEPs only differ by one index, compare it.
3409 unsigned NumDifferences = 0; // Keep track of # differences.
3410 unsigned DiffOperand = 0; // The operand that differs.
3411 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3412 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00003413 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3414 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003415 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00003416 NumDifferences = 2;
3417 break;
3418 } else {
3419 if (NumDifferences++) break;
3420 DiffOperand = i;
3421 }
3422 }
3423
3424 if (NumDifferences == 0) // SAME GEP?
3425 return ReplaceInstUsesWith(I, // No comparison is needed here.
3426 ConstantBool::get(Cond == Instruction::SetEQ));
3427 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003428 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3429 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00003430
3431 // Convert the operands to signed values to make sure to perform a
3432 // signed comparison.
3433 const Type *NewTy = LHSV->getType()->getSignedVersion();
3434 if (LHSV->getType() != NewTy)
3435 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3436 LHSV->getName()), I);
3437 if (RHSV->getType() != NewTy)
3438 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3439 RHSV->getName()), I);
3440 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003441 }
3442 }
3443
Chris Lattner574da9b2005-01-13 20:14:25 +00003444 // Only lower this if the setcc is the only user of the GEP or if we expect
3445 // the result to fold to a constant!
3446 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3447 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3448 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3449 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3450 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3451 return new SetCondInst(Cond, L, R);
3452 }
3453 }
3454 return 0;
3455}
3456
3457
Chris Lattner484d3cf2005-04-24 06:59:08 +00003458Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003459 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00003460 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3461 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00003462
3463 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00003464 if (Op0 == Op1)
3465 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00003466
Chris Lattnere87597f2004-10-16 18:11:37 +00003467 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3468 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3469
Chris Lattner711b3402004-11-14 07:33:16 +00003470 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3471 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00003472 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3473 isa<ConstantPointerNull>(Op0)) &&
3474 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00003475 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00003476 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3477
3478 // setcc's with boolean values can always be turned into bitwise operations
3479 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00003480 switch (I.getOpcode()) {
3481 default: assert(0 && "Invalid setcc instruction!");
3482 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00003483 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00003484 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00003485 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00003486 }
Chris Lattner5dbef222004-08-11 00:50:51 +00003487 case Instruction::SetNE:
3488 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00003489
Chris Lattner5dbef222004-08-11 00:50:51 +00003490 case Instruction::SetGT:
3491 std::swap(Op0, Op1); // Change setgt -> setlt
3492 // FALL THROUGH
3493 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3494 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3495 InsertNewInstBefore(Not, I);
3496 return BinaryOperator::createAnd(Not, Op1);
3497 }
3498 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00003499 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00003500 // FALL THROUGH
3501 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3502 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3503 InsertNewInstBefore(Not, I);
3504 return BinaryOperator::createOr(Not, Op1);
3505 }
3506 }
Chris Lattner8b170942002-08-09 23:47:40 +00003507 }
3508
Chris Lattner2be51ae2004-06-09 04:24:29 +00003509 // See if we are doing a comparison between a constant and an instruction that
3510 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00003511 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003512 // Check to see if we are comparing against the minimum or maximum value...
3513 if (CI->isMinValue()) {
3514 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3515 return ReplaceInstUsesWith(I, ConstantBool::False);
3516 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3517 return ReplaceInstUsesWith(I, ConstantBool::True);
3518 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3519 return BinaryOperator::createSetEQ(Op0, Op1);
3520 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3521 return BinaryOperator::createSetNE(Op0, Op1);
3522
3523 } else if (CI->isMaxValue()) {
3524 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3525 return ReplaceInstUsesWith(I, ConstantBool::False);
3526 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3527 return ReplaceInstUsesWith(I, ConstantBool::True);
3528 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3529 return BinaryOperator::createSetEQ(Op0, Op1);
3530 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3531 return BinaryOperator::createSetNE(Op0, Op1);
3532
3533 // Comparing against a value really close to min or max?
3534 } else if (isMinValuePlusOne(CI)) {
3535 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3536 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3537 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3538 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3539
3540 } else if (isMaxValueMinusOne(CI)) {
3541 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3542 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3543 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3544 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3545 }
3546
3547 // If we still have a setle or setge instruction, turn it into the
3548 // appropriate setlt or setgt instruction. Since the border cases have
3549 // already been handled above, this requires little checking.
3550 //
3551 if (I.getOpcode() == Instruction::SetLE)
3552 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3553 if (I.getOpcode() == Instruction::SetGE)
3554 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3555
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003556
3557 // See if we can fold the comparison based on bits known to be zero or one
3558 // in the input.
3559 uint64_t KnownZero, KnownOne;
3560 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3561 KnownZero, KnownOne, 0))
3562 return &I;
3563
3564 // Given the known and unknown bits, compute a range that the LHS could be
3565 // in.
3566 if (KnownOne | KnownZero) {
3567 if (Ty->isUnsigned()) { // Unsigned comparison.
3568 uint64_t Min, Max;
3569 uint64_t RHSVal = CI->getZExtValue();
3570 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3571 Min, Max);
3572 switch (I.getOpcode()) { // LE/GE have been folded already.
3573 default: assert(0 && "Unknown setcc opcode!");
3574 case Instruction::SetEQ:
3575 if (Max < RHSVal || Min > RHSVal)
3576 return ReplaceInstUsesWith(I, ConstantBool::False);
3577 break;
3578 case Instruction::SetNE:
3579 if (Max < RHSVal || Min > RHSVal)
3580 return ReplaceInstUsesWith(I, ConstantBool::True);
3581 break;
3582 case Instruction::SetLT:
3583 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3584 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3585 break;
3586 case Instruction::SetGT:
3587 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3588 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3589 break;
3590 }
3591 } else { // Signed comparison.
3592 int64_t Min, Max;
3593 int64_t RHSVal = CI->getSExtValue();
3594 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3595 Min, Max);
3596 switch (I.getOpcode()) { // LE/GE have been folded already.
3597 default: assert(0 && "Unknown setcc opcode!");
3598 case Instruction::SetEQ:
3599 if (Max < RHSVal || Min > RHSVal)
3600 return ReplaceInstUsesWith(I, ConstantBool::False);
3601 break;
3602 case Instruction::SetNE:
3603 if (Max < RHSVal || Min > RHSVal)
3604 return ReplaceInstUsesWith(I, ConstantBool::True);
3605 break;
3606 case Instruction::SetLT:
3607 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3608 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3609 break;
3610 case Instruction::SetGT:
3611 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3612 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3613 break;
3614 }
3615 }
3616 }
3617
3618
Chris Lattner3c6a0d42004-05-25 06:32:08 +00003619 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00003620 switch (LHSI->getOpcode()) {
3621 case Instruction::And:
3622 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3623 LHSI->getOperand(0)->hasOneUse()) {
3624 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3625 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3626 // happens a LOT in code produced by the C front-end, for bitfield
3627 // access.
3628 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003629 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3630
3631 // Check to see if there is a noop-cast between the shift and the and.
3632 if (!Shift) {
3633 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3634 if (CI->getOperand(0)->getType()->isIntegral() &&
3635 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3636 CI->getType()->getPrimitiveSizeInBits())
3637 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3638 }
3639
Chris Lattner648e3bc2004-09-23 21:52:49 +00003640 ConstantUInt *ShAmt;
3641 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003642 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3643 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00003644
Chris Lattner648e3bc2004-09-23 21:52:49 +00003645 // We can fold this as long as we can't shift unknown bits
3646 // into the mask. This can only happen with signed shift
3647 // rights, as they sign-extend.
3648 if (ShAmt) {
3649 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003650 Ty->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00003651 if (!CanFold) {
3652 // To test for the bad case of the signed shr, see if any
3653 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00003654 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3655 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3656
3657 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00003658 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003659 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3660 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00003661 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3662 CanFold = true;
3663 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003664
Chris Lattner648e3bc2004-09-23 21:52:49 +00003665 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00003666 Constant *NewCst;
3667 if (Shift->getOpcode() == Instruction::Shl)
3668 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3669 else
3670 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003671
Chris Lattner648e3bc2004-09-23 21:52:49 +00003672 // Check to see if we are shifting out any of the bits being
3673 // compared.
3674 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3675 // If we shifted bits out, the fold is not going to work out.
3676 // As a special case, check to see if this means that the
3677 // result is always true or false now.
3678 if (I.getOpcode() == Instruction::SetEQ)
3679 return ReplaceInstUsesWith(I, ConstantBool::False);
3680 if (I.getOpcode() == Instruction::SetNE)
3681 return ReplaceInstUsesWith(I, ConstantBool::True);
3682 } else {
3683 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00003684 Constant *NewAndCST;
3685 if (Shift->getOpcode() == Instruction::Shl)
3686 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3687 else
3688 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3689 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003690 if (AndTy == Ty)
3691 LHSI->setOperand(0, Shift->getOperand(0));
3692 else {
3693 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3694 *Shift);
3695 LHSI->setOperand(0, NewCast);
3696 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003697 WorkList.push_back(Shift); // Shift is dead.
3698 AddUsesToWorkList(I);
3699 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00003700 }
3701 }
Chris Lattner457dd822004-06-09 07:59:58 +00003702 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003703 }
3704 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00003705
Chris Lattner18d19ca2004-09-28 18:22:15 +00003706 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3707 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3708 switch (I.getOpcode()) {
3709 default: break;
3710 case Instruction::SetEQ:
3711 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003712 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3713
3714 // Check that the shift amount is in range. If not, don't perform
3715 // undefined shifts. When the shift is visited it will be
3716 // simplified.
3717 if (ShAmt->getValue() >= TypeBits)
3718 break;
3719
Chris Lattner18d19ca2004-09-28 18:22:15 +00003720 // If we are comparing against bits always shifted out, the
3721 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003722 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00003723 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3724 if (Comp != CI) {// Comparing against a bit that we know is zero.
3725 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3726 Constant *Cst = ConstantBool::get(IsSetNE);
3727 return ReplaceInstUsesWith(I, Cst);
3728 }
3729
3730 if (LHSI->hasOneUse()) {
3731 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00003732 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003733 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3734
3735 Constant *Mask;
3736 if (CI->getType()->isUnsigned()) {
3737 Mask = ConstantUInt::get(CI->getType(), Val);
3738 } else if (ShAmtVal != 0) {
3739 Mask = ConstantSInt::get(CI->getType(), Val);
3740 } else {
3741 Mask = ConstantInt::getAllOnesValue(CI->getType());
3742 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003743
Chris Lattner18d19ca2004-09-28 18:22:15 +00003744 Instruction *AndI =
3745 BinaryOperator::createAnd(LHSI->getOperand(0),
3746 Mask, LHSI->getName()+".mask");
3747 Value *And = InsertNewInstBefore(AndI, I);
3748 return new SetCondInst(I.getOpcode(), And,
3749 ConstantExpr::getUShr(CI, ShAmt));
3750 }
3751 }
3752 }
3753 }
3754 break;
3755
Chris Lattner83c4ec02004-09-27 19:29:18 +00003756 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00003757 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00003758 switch (I.getOpcode()) {
3759 default: break;
3760 case Instruction::SetEQ:
3761 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003762
3763 // Check that the shift amount is in range. If not, don't perform
3764 // undefined shifts. When the shift is visited it will be
3765 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00003766 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00003767 if (ShAmt->getValue() >= TypeBits)
3768 break;
3769
Chris Lattnerf63f6472004-09-27 16:18:50 +00003770 // If we are comparing against bits always shifted out, the
3771 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003772 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00003773 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00003774
Chris Lattnerf63f6472004-09-27 16:18:50 +00003775 if (Comp != CI) {// Comparing against a bit that we know is zero.
3776 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3777 Constant *Cst = ConstantBool::get(IsSetNE);
3778 return ReplaceInstUsesWith(I, Cst);
3779 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003780
Chris Lattnerf63f6472004-09-27 16:18:50 +00003781 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003782 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003783
Chris Lattnerf63f6472004-09-27 16:18:50 +00003784 // Otherwise strength reduce the shift into an and.
3785 uint64_t Val = ~0ULL; // All ones.
3786 Val <<= ShAmtVal; // Shift over to the right spot.
3787
3788 Constant *Mask;
3789 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00003790 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00003791 Mask = ConstantUInt::get(CI->getType(), Val);
3792 } else {
3793 Mask = ConstantSInt::get(CI->getType(), Val);
3794 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003795
Chris Lattnerf63f6472004-09-27 16:18:50 +00003796 Instruction *AndI =
3797 BinaryOperator::createAnd(LHSI->getOperand(0),
3798 Mask, LHSI->getName()+".mask");
3799 Value *And = InsertNewInstBefore(AndI, I);
3800 return new SetCondInst(I.getOpcode(), And,
3801 ConstantExpr::getShl(CI, ShAmt));
3802 }
3803 break;
3804 }
3805 }
3806 }
3807 break;
Chris Lattner0c967662004-09-24 15:21:34 +00003808
Chris Lattnera96879a2004-09-29 17:40:11 +00003809 case Instruction::Div:
3810 // Fold: (div X, C1) op C2 -> range check
3811 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3812 // Fold this div into the comparison, producing a range check.
3813 // Determine, based on the divide type, what the range is being
3814 // checked. If there is an overflow on the low or high side, remember
3815 // it, otherwise compute the range [low, hi) bounding the new value.
3816 bool LoOverflow = false, HiOverflow = 0;
3817 ConstantInt *LoBound = 0, *HiBound = 0;
3818
3819 ConstantInt *Prod;
3820 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3821
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003822 Instruction::BinaryOps Opcode = I.getOpcode();
3823
Chris Lattnera96879a2004-09-29 17:40:11 +00003824 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3825 } else if (LHSI->getType()->isUnsigned()) { // udiv
3826 LoBound = Prod;
3827 LoOverflow = ProdOV;
3828 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3829 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3830 if (CI->isNullValue()) { // (X / pos) op 0
3831 // Can't overflow.
3832 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3833 HiBound = DivRHS;
3834 } else if (isPositive(CI)) { // (X / pos) op pos
3835 LoBound = Prod;
3836 LoOverflow = ProdOV;
3837 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3838 } else { // (X / pos) op neg
3839 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3840 LoOverflow = AddWithOverflow(LoBound, Prod,
3841 cast<ConstantInt>(DivRHSH));
3842 HiBound = Prod;
3843 HiOverflow = ProdOV;
3844 }
3845 } else { // Divisor is < 0.
3846 if (CI->isNullValue()) { // (X / neg) op 0
3847 LoBound = AddOne(DivRHS);
3848 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00003849 if (HiBound == DivRHS)
3850 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00003851 } else if (isPositive(CI)) { // (X / neg) op pos
3852 HiOverflow = LoOverflow = ProdOV;
3853 if (!LoOverflow)
3854 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3855 HiBound = AddOne(Prod);
3856 } else { // (X / neg) op neg
3857 LoBound = Prod;
3858 LoOverflow = HiOverflow = ProdOV;
3859 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3860 }
Chris Lattner340a05f2004-10-08 19:15:44 +00003861
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003862 // Dividing by a negate swaps the condition.
3863 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00003864 }
3865
3866 if (LoBound) {
3867 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003868 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003869 default: assert(0 && "Unhandled setcc opcode!");
3870 case Instruction::SetEQ:
3871 if (LoOverflow && HiOverflow)
3872 return ReplaceInstUsesWith(I, ConstantBool::False);
3873 else if (HiOverflow)
3874 return new SetCondInst(Instruction::SetGE, X, LoBound);
3875 else if (LoOverflow)
3876 return new SetCondInst(Instruction::SetLT, X, HiBound);
3877 else
3878 return InsertRangeTest(X, LoBound, HiBound, true, I);
3879 case Instruction::SetNE:
3880 if (LoOverflow && HiOverflow)
3881 return ReplaceInstUsesWith(I, ConstantBool::True);
3882 else if (HiOverflow)
3883 return new SetCondInst(Instruction::SetLT, X, LoBound);
3884 else if (LoOverflow)
3885 return new SetCondInst(Instruction::SetGE, X, HiBound);
3886 else
3887 return InsertRangeTest(X, LoBound, HiBound, false, I);
3888 case Instruction::SetLT:
3889 if (LoOverflow)
3890 return ReplaceInstUsesWith(I, ConstantBool::False);
3891 return new SetCondInst(Instruction::SetLT, X, LoBound);
3892 case Instruction::SetGT:
3893 if (HiOverflow)
3894 return ReplaceInstUsesWith(I, ConstantBool::False);
3895 return new SetCondInst(Instruction::SetGE, X, HiBound);
3896 }
3897 }
3898 }
3899 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00003900 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003901
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003902 // Simplify seteq and setne instructions...
3903 if (I.getOpcode() == Instruction::SetEQ ||
3904 I.getOpcode() == Instruction::SetNE) {
3905 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3906
Chris Lattner00b1a7e2003-07-23 17:26:36 +00003907 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003908 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00003909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3910 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00003911 case Instruction::Rem:
3912 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3913 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3914 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003915 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3916 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3917 if (isPowerOf2_64(V)) {
3918 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003919 const Type *UTy = BO->getType()->getUnsignedVersion();
3920 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3921 UTy, "tmp"), I);
3922 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3923 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3924 RHSCst, BO->getName()), I);
3925 return BinaryOperator::create(I.getOpcode(), NewRem,
3926 Constant::getNullValue(UTy));
3927 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003928 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003929 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003930
Chris Lattner934754b2003-08-13 05:33:12 +00003931 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003932 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3933 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003934 if (BO->hasOneUse())
3935 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3936 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003937 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003938 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3939 // efficiently invertible, or if the add has just this one use.
3940 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003941
Chris Lattner934754b2003-08-13 05:33:12 +00003942 if (Value *NegVal = dyn_castNegVal(BOp1))
3943 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3944 else if (Value *NegVal = dyn_castNegVal(BOp0))
3945 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003946 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003947 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3948 BO->setName("");
3949 InsertNewInstBefore(Neg, I);
3950 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3951 }
3952 }
3953 break;
3954 case Instruction::Xor:
3955 // For the xor case, we can xor two constants together, eliminating
3956 // the explicit xor.
3957 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3958 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003959 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003960
3961 // FALLTHROUGH
3962 case Instruction::Sub:
3963 // Replace (([sub|xor] A, B) != 0) with (A != B)
3964 if (CI->isNullValue())
3965 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3966 BO->getOperand(1));
3967 break;
3968
3969 case Instruction::Or:
3970 // If bits are being or'd in that are not present in the constant we
3971 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003972 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003973 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003974 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003975 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003976 }
Chris Lattner934754b2003-08-13 05:33:12 +00003977 break;
3978
3979 case Instruction::And:
3980 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003981 // If bits are being compared against that are and'd out, then the
3982 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003983 if (!ConstantExpr::getAnd(CI,
3984 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003985 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003986
Chris Lattner457dd822004-06-09 07:59:58 +00003987 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003988 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003989 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3990 Instruction::SetNE, Op0,
3991 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003992
Chris Lattner934754b2003-08-13 05:33:12 +00003993 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3994 // to be a signed value as appropriate.
3995 if (isSignBit(BOC)) {
3996 Value *X = BO->getOperand(0);
3997 // If 'X' is not signed, insert a cast now...
3998 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003999 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00004000 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00004001 }
4002 return new SetCondInst(isSetNE ? Instruction::SetLT :
4003 Instruction::SetGE, X,
4004 Constant::getNullValue(X->getType()));
4005 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004006
Chris Lattner83c4ec02004-09-27 19:29:18 +00004007 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004008 if (CI->isNullValue() && isHighOnes(BOC)) {
4009 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004010 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004011
4012 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00004013 if (NegX->getType()->isSigned()) {
4014 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4015 X = InsertCastBefore(X, DestTy, I);
4016 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004017 }
4018
4019 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00004020 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004021 }
4022
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004023 }
Chris Lattner934754b2003-08-13 05:33:12 +00004024 default: break;
4025 }
4026 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004027 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00004028 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004029 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4030 Value *CastOp = Cast->getOperand(0);
4031 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004032 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004033 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004034 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004035 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004036 "Source and destination signednesses should differ!");
4037 if (Cast->getType()->isSigned()) {
4038 // If this is a signed comparison, check for comparisons in the
4039 // vicinity of zero.
4040 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4041 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00004042 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00004043 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004044 else if (I.getOpcode() == Instruction::SetGT &&
4045 cast<ConstantSInt>(CI)->getValue() == -1)
4046 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00004047 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00004048 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004049 } else {
4050 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4051 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004052 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004053 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00004054 return BinaryOperator::createSetGT(CastOp,
4055 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004056 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004057 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004058 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00004059 return BinaryOperator::createSetLT(CastOp,
4060 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004061 }
4062 }
4063 }
Chris Lattner40f5d702003-06-04 05:10:11 +00004064 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004065 }
4066
Chris Lattner6970b662005-04-23 15:31:55 +00004067 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4068 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4069 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4070 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004071 case Instruction::GetElementPtr:
4072 if (RHSC->isNullValue()) {
4073 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4074 bool isAllZeros = true;
4075 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4076 if (!isa<Constant>(LHSI->getOperand(i)) ||
4077 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4078 isAllZeros = false;
4079 break;
4080 }
4081 if (isAllZeros)
4082 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4083 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4084 }
4085 break;
4086
Chris Lattner6970b662005-04-23 15:31:55 +00004087 case Instruction::PHI:
4088 if (Instruction *NV = FoldOpIntoPhi(I))
4089 return NV;
4090 break;
4091 case Instruction::Select:
4092 // If either operand of the select is a constant, we can fold the
4093 // comparison into the select arms, which will cause one to be
4094 // constant folded and the select turned into a bitwise or.
4095 Value *Op1 = 0, *Op2 = 0;
4096 if (LHSI->hasOneUse()) {
4097 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4098 // Fold the known value into the constant operand.
4099 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4100 // Insert a new SetCC of the other select operand.
4101 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4102 LHSI->getOperand(2), RHSC,
4103 I.getName()), I);
4104 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4105 // Fold the known value into the constant operand.
4106 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4107 // Insert a new SetCC of the other select operand.
4108 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4109 LHSI->getOperand(1), RHSC,
4110 I.getName()), I);
4111 }
4112 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004113
Chris Lattner6970b662005-04-23 15:31:55 +00004114 if (Op1)
4115 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4116 break;
4117 }
4118 }
4119
Chris Lattner574da9b2005-01-13 20:14:25 +00004120 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4121 if (User *GEP = dyn_castGetElementPtr(Op0))
4122 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4123 return NI;
4124 if (User *GEP = dyn_castGetElementPtr(Op1))
4125 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4126 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4127 return NI;
4128
Chris Lattnerde90b762003-11-03 04:25:02 +00004129 // Test to see if the operands of the setcc are casted versions of other
4130 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00004131 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4132 Value *CastOp0 = CI->getOperand(0);
4133 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00004134 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00004135 (I.getOpcode() == Instruction::SetEQ ||
4136 I.getOpcode() == Instruction::SetNE)) {
4137 // We keep moving the cast from the left operand over to the right
4138 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00004139 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00004140
Chris Lattnerde90b762003-11-03 04:25:02 +00004141 // If operand #1 is a cast instruction, see if we can eliminate it as
4142 // well.
Chris Lattner68708052003-11-03 05:17:03 +00004143 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4144 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00004145 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00004146 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00004147
Chris Lattnerde90b762003-11-03 04:25:02 +00004148 // If Op1 is a constant, we can fold the cast into the constant.
4149 if (Op1->getType() != Op0->getType())
4150 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4151 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4152 } else {
4153 // Otherwise, cast the RHS right before the setcc
4154 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4155 InsertNewInstBefore(cast<Instruction>(Op1), I);
4156 }
4157 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4158 }
4159
Chris Lattner68708052003-11-03 05:17:03 +00004160 // Handle the special case of: setcc (cast bool to X), <cst>
4161 // This comes up when you have code like
4162 // int X = A < B;
4163 // if (X) ...
4164 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00004165 // with a constant or another cast from the same type.
4166 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4167 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4168 return R;
Chris Lattner68708052003-11-03 05:17:03 +00004169 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00004170
4171 if (I.getOpcode() == Instruction::SetNE ||
4172 I.getOpcode() == Instruction::SetEQ) {
4173 Value *A, *B;
4174 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4175 (A == Op1 || B == Op1)) {
4176 // (A^B) == A -> B == 0
4177 Value *OtherVal = A == Op1 ? B : A;
4178 return BinaryOperator::create(I.getOpcode(), OtherVal,
4179 Constant::getNullValue(A->getType()));
4180 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4181 (A == Op0 || B == Op0)) {
4182 // A == (A^B) -> B == 0
4183 Value *OtherVal = A == Op0 ? B : A;
4184 return BinaryOperator::create(I.getOpcode(), OtherVal,
4185 Constant::getNullValue(A->getType()));
4186 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4187 // (A-B) == A -> B == 0
4188 return BinaryOperator::create(I.getOpcode(), B,
4189 Constant::getNullValue(B->getType()));
4190 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4191 // A == (A-B) -> B == 0
4192 return BinaryOperator::create(I.getOpcode(), B,
4193 Constant::getNullValue(B->getType()));
4194 }
4195 }
Chris Lattner7e708292002-06-25 16:13:24 +00004196 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004197}
4198
Chris Lattner484d3cf2005-04-24 06:59:08 +00004199// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4200// We only handle extending casts so far.
4201//
4202Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4203 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4204 const Type *SrcTy = LHSCIOp->getType();
4205 const Type *DestTy = SCI.getOperand(0)->getType();
4206 Value *RHSCIOp;
4207
4208 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004209 return 0;
4210
Chris Lattner484d3cf2005-04-24 06:59:08 +00004211 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4212 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4213 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4214
4215 // Is this a sign or zero extension?
4216 bool isSignSrc = SrcTy->isSigned();
4217 bool isSignDest = DestTy->isSigned();
4218
4219 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4220 // Not an extension from the same type?
4221 RHSCIOp = CI->getOperand(0);
4222 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4223 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4224 // Compute the constant that would happen if we truncated to SrcTy then
4225 // reextended to DestTy.
4226 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4227
4228 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4229 RHSCIOp = Res;
4230 } else {
4231 // If the value cannot be represented in the shorter type, we cannot emit
4232 // a simple comparison.
4233 if (SCI.getOpcode() == Instruction::SetEQ)
4234 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4235 if (SCI.getOpcode() == Instruction::SetNE)
4236 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4237
Chris Lattner484d3cf2005-04-24 06:59:08 +00004238 // Evaluate the comparison for LT.
4239 Value *Result;
4240 if (DestTy->isSigned()) {
4241 // We're performing a signed comparison.
4242 if (isSignSrc) {
4243 // Signed extend and signed comparison.
4244 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4245 Result = ConstantBool::False;
4246 else
4247 Result = ConstantBool::True; // X < (large) --> true
4248 } else {
4249 // Unsigned extend and signed comparison.
4250 if (cast<ConstantSInt>(CI)->getValue() < 0)
4251 Result = ConstantBool::False;
4252 else
4253 Result = ConstantBool::True;
4254 }
4255 } else {
4256 // We're performing an unsigned comparison.
4257 if (!isSignSrc) {
4258 // Unsigned extend & compare -> always true.
4259 Result = ConstantBool::True;
4260 } else {
4261 // We're performing an unsigned comp with a sign extended value.
4262 // This is true if the input is >= 0. [aka >s -1]
4263 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4264 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4265 NegOne, SCI.getName()), SCI);
4266 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00004267 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004268
Jeff Cohen00b168892005-07-27 06:12:32 +00004269 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004270 if (SCI.getOpcode() == Instruction::SetLT) {
4271 return ReplaceInstUsesWith(SCI, Result);
4272 } else {
4273 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4274 if (Constant *CI = dyn_cast<Constant>(Result))
4275 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4276 else
4277 return BinaryOperator::createNot(Result);
4278 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004279 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00004280 } else {
4281 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00004282 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004283
Chris Lattner8d7089e2005-06-16 03:00:08 +00004284 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00004285 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4286}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004287
Chris Lattnerea340052003-03-10 19:16:08 +00004288Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00004289 assert(I.getOperand(1)->getType() == Type::UByteTy);
4290 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00004291 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004292
4293 // shl X, 0 == X and shr X, 0 == X
4294 // shl 0, X == 0 and shr 0, X == 0
4295 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00004296 Op0 == Constant::getNullValue(Op0->getType()))
4297 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004298
Chris Lattnere87597f2004-10-16 18:11:37 +00004299 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4300 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00004301 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00004302 else // undef << X -> 0 AND undef >>u X -> 0
4303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4304 }
4305 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00004306 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00004307 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4308 else
4309 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4310 }
4311
Chris Lattnerdf17af12003-08-12 21:53:41 +00004312 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4313 if (!isLeftShift)
4314 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4315 if (CSI->isAllOnesValue())
4316 return ReplaceInstUsesWith(I, CSI);
4317
Chris Lattner2eefe512004-04-09 19:05:30 +00004318 // Try to fold constant and into select arguments.
4319 if (isa<Constant>(Op0))
4320 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004321 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004322 return R;
4323
Chris Lattner120347e2005-05-08 17:34:56 +00004324 // See if we can turn a signed shr into an unsigned shr.
4325 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00004326 if (MaskedValueIsZero(Op0,
4327 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00004328 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4329 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4330 I.getName()), I);
4331 return new CastInst(V, I.getType());
4332 }
4333 }
Jeff Cohen00b168892005-07-27 06:12:32 +00004334
Chris Lattner4d5542c2006-01-06 07:12:35 +00004335 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4336 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4337 return Res;
4338 return 0;
4339}
4340
4341Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4342 ShiftInst &I) {
4343 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00004344 bool isSignedShift = Op0->getType()->isSigned();
4345 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004346
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004347 // See if we can simplify any instructions used by the instruction whose sole
4348 // purpose is to compute bits we don't care about.
4349 uint64_t KnownZero, KnownOne;
4350 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4351 KnownZero, KnownOne))
4352 return &I;
4353
Chris Lattner4d5542c2006-01-06 07:12:35 +00004354 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4355 // of a signed value.
4356 //
4357 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4358 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00004359 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00004360 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4361 else {
4362 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4363 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004364 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004365 }
4366
4367 // ((X*C1) << C2) == (X * (C1 << C2))
4368 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4369 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4370 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4371 return BinaryOperator::createMul(BO->getOperand(0),
4372 ConstantExpr::getShl(BOOp, Op1));
4373
4374 // Try to fold constant and into select arguments.
4375 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4376 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4377 return R;
4378 if (isa<PHINode>(Op0))
4379 if (Instruction *NV = FoldOpIntoPhi(I))
4380 return NV;
4381
4382 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004383 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4384 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4385 Value *V1, *V2;
4386 ConstantInt *CC;
4387 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004388 default: break;
4389 case Instruction::Add:
4390 case Instruction::And:
4391 case Instruction::Or:
4392 case Instruction::Xor:
4393 // These operators commute.
4394 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004395 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4396 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004397 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004398 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004399 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004400 Op0BO->getName());
4401 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004402 Instruction *X =
4403 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4404 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004405 InsertNewInstBefore(X, I); // (X + (Y << C))
4406 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004407 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004408 return BinaryOperator::createAnd(X, C2);
4409 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004410
Chris Lattner150f12a2005-09-18 06:30:59 +00004411 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4412 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4413 match(Op0BO->getOperand(1),
4414 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004415 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004416 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004417 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004418 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004419 Op0BO->getName());
4420 InsertNewInstBefore(YS, I); // (Y << C)
4421 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004422 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004423 V1->getName()+".mask");
4424 InsertNewInstBefore(XM, I); // X & (CC << C)
4425
4426 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4427 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004428
Chris Lattner150f12a2005-09-18 06:30:59 +00004429 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00004430 case Instruction::Sub:
4431 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004432 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4433 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004434 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004435 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004436 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004437 Op0BO->getName());
4438 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004439 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00004440 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004441 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004442 InsertNewInstBefore(X, I); // (X + (Y << C))
4443 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004444 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004445 return BinaryOperator::createAnd(X, C2);
4446 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004447
Chris Lattner13d4ab42006-05-31 21:14:00 +00004448 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004449 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4450 match(Op0BO->getOperand(0),
4451 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004452 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004453 cast<BinaryOperator>(Op0BO->getOperand(0))
4454 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004455 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004456 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004457 Op0BO->getName());
4458 InsertNewInstBefore(YS, I); // (Y << C)
4459 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004460 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004461 V1->getName()+".mask");
4462 InsertNewInstBefore(XM, I); // X & (CC << C)
4463
Chris Lattner13d4ab42006-05-31 21:14:00 +00004464 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00004465 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004466
Chris Lattner11021cb2005-09-18 05:12:10 +00004467 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004468 }
4469
4470
4471 // If the operand is an bitwise operator with a constant RHS, and the
4472 // shift is the only use, we can pull it out of the shift.
4473 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4474 bool isValid = true; // Valid only for And, Or, Xor
4475 bool highBitSet = false; // Transform if high bit of constant set?
4476
4477 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004478 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004479 case Instruction::Add:
4480 isValid = isLeftShift;
4481 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004482 case Instruction::Or:
4483 case Instruction::Xor:
4484 highBitSet = false;
4485 break;
4486 case Instruction::And:
4487 highBitSet = true;
4488 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004489 }
4490
4491 // If this is a signed shift right, and the high bit is modified
4492 // by the logical operation, do not perform the transformation.
4493 // The highBitSet boolean indicates the value of the high bit of
4494 // the constant which would cause it to be modified for this
4495 // operation.
4496 //
Chris Lattner830ed032006-01-06 07:22:22 +00004497 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004498 uint64_t Val = Op0C->getRawValue();
4499 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4500 }
4501
4502 if (isValid) {
4503 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4504
4505 Instruction *NewShift =
4506 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4507 Op0BO->getName());
4508 Op0BO->setName("");
4509 InsertNewInstBefore(NewShift, I);
4510
4511 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4512 NewRHS);
4513 }
4514 }
4515 }
4516 }
4517
Chris Lattnerad0124c2006-01-06 07:52:12 +00004518 // Find out if this is a shift of a shift by a constant.
4519 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004520 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00004521 ShiftOp = Op0SI;
4522 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4523 // If this is a noop-integer case of a shift instruction, use the shift.
4524 if (CI->getOperand(0)->getType()->isInteger() &&
4525 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4526 CI->getType()->getPrimitiveSizeInBits() &&
4527 isa<ShiftInst>(CI->getOperand(0))) {
4528 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4529 }
4530 }
4531
4532 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4533 // Find the operands and properties of the input shift. Note that the
4534 // signedness of the input shift may differ from the current shift if there
4535 // is a noop cast between the two.
4536 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4537 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00004538 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004539
4540 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4541
4542 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4543 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4544
4545 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4546 if (isLeftShift == isShiftOfLeftShift) {
4547 // Do not fold these shifts if the first one is signed and the second one
4548 // is unsigned and this is a right shift. Further, don't do any folding
4549 // on them.
4550 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4551 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004552
Chris Lattnerad0124c2006-01-06 07:52:12 +00004553 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4554 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4555 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00004556
Chris Lattnerad0124c2006-01-06 07:52:12 +00004557 Value *Op = ShiftOp->getOperand(0);
4558 if (isShiftOfSignedShift != isSignedShift)
4559 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4560 return new ShiftInst(I.getOpcode(), Op,
4561 ConstantUInt::get(Type::UByteTy, Amt));
4562 }
4563
4564 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4565 // signed types, we can only support the (A >> c1) << c2 configuration,
4566 // because it can not turn an arbitrary bit of A into a sign bit.
4567 if (isUnsignedShift || isLeftShift) {
4568 // Calculate bitmask for what gets shifted off the edge.
4569 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4570 if (isLeftShift)
4571 C = ConstantExpr::getShl(C, ShiftAmt1C);
4572 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00004573 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004574
4575 Value *Op = ShiftOp->getOperand(0);
4576 if (isShiftOfSignedShift != isSignedShift)
4577 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4578
4579 Instruction *Mask =
4580 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4581 InsertNewInstBefore(Mask, I);
4582
4583 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00004584 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004585 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00004586 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004587 return new ShiftInst(I.getOpcode(), Mask,
4588 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004589 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4590 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4591 // Make sure to emit an unsigned shift right, not a signed one.
4592 Mask = InsertNewInstBefore(new CastInst(Mask,
4593 Mask->getType()->getUnsignedVersion(),
4594 Op->getName()), I);
4595 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00004596 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004597 InsertNewInstBefore(Mask, I);
4598 return new CastInst(Mask, I.getType());
4599 } else {
4600 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4601 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4602 }
4603 } else {
4604 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4605 Op = InsertNewInstBefore(new CastInst(Mask,
4606 I.getType()->getSignedVersion(),
4607 Mask->getName()), I);
4608 Instruction *Shift =
4609 new ShiftInst(ShiftOp->getOpcode(), Op,
4610 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4611 InsertNewInstBefore(Shift, I);
4612
4613 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4614 C = ConstantExpr::getShl(C, Op1);
4615 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4616 InsertNewInstBefore(Mask, I);
4617 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00004618 }
4619 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00004620 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00004621 // this case, C1 == C2 and C1 is 8, 16, or 32.
4622 if (ShiftAmt1 == ShiftAmt2) {
4623 const Type *SExtType = 0;
Chris Lattner94046b42006-04-28 22:21:41 +00004624 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004625 case 8 : SExtType = Type::SByteTy; break;
4626 case 16: SExtType = Type::ShortTy; break;
4627 case 32: SExtType = Type::IntTy; break;
4628 }
4629
4630 if (SExtType) {
4631 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4632 SExtType, "sext");
4633 InsertNewInstBefore(NewTrunc, I);
4634 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00004635 }
Chris Lattner11021cb2005-09-18 05:12:10 +00004636 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00004637 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004638 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004639 return 0;
4640}
4641
Chris Lattnera1be5662002-05-02 17:06:02 +00004642
Chris Lattnercfd65102005-10-29 04:36:15 +00004643/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4644/// expression. If so, decompose it, returning some value X, such that Val is
4645/// X*Scale+Offset.
4646///
4647static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4648 unsigned &Offset) {
4649 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4650 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4651 Offset = CI->getValue();
4652 Scale = 1;
4653 return ConstantUInt::get(Type::UIntTy, 0);
4654 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4655 if (I->getNumOperands() == 2) {
4656 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4657 if (I->getOpcode() == Instruction::Shl) {
4658 // This is a value scaled by '1 << the shift amt'.
4659 Scale = 1U << CUI->getValue();
4660 Offset = 0;
4661 return I->getOperand(0);
4662 } else if (I->getOpcode() == Instruction::Mul) {
4663 // This value is scaled by 'CUI'.
4664 Scale = CUI->getValue();
4665 Offset = 0;
4666 return I->getOperand(0);
4667 } else if (I->getOpcode() == Instruction::Add) {
4668 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4669 // divisible by C2.
4670 unsigned SubScale;
4671 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4672 Offset);
4673 Offset += CUI->getValue();
4674 if (SubScale > 1 && (Offset % SubScale == 0)) {
4675 Scale = SubScale;
4676 return SubVal;
4677 }
4678 }
4679 }
4680 }
4681 }
4682
4683 // Otherwise, we can't look past this.
4684 Scale = 1;
4685 Offset = 0;
4686 return Val;
4687}
4688
4689
Chris Lattnerb3f83972005-10-24 06:03:58 +00004690/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4691/// try to eliminate the cast by moving the type information into the alloc.
4692Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4693 AllocationInst &AI) {
4694 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004695 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00004696
Chris Lattnerb53c2382005-10-24 06:22:12 +00004697 // Remove any uses of AI that are dead.
4698 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4699 std::vector<Instruction*> DeadUsers;
4700 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4701 Instruction *User = cast<Instruction>(*UI++);
4702 if (isInstructionTriviallyDead(User)) {
4703 while (UI != E && *UI == User)
4704 ++UI; // If this instruction uses AI more than once, don't break UI.
4705
4706 // Add operands to the worklist.
4707 AddUsesToWorkList(*User);
4708 ++NumDeadInst;
4709 DEBUG(std::cerr << "IC: DCE: " << *User);
4710
4711 User->eraseFromParent();
4712 removeFromWorkList(User);
4713 }
4714 }
4715
Chris Lattnerb3f83972005-10-24 06:03:58 +00004716 // Get the type really allocated and the type casted to.
4717 const Type *AllocElTy = AI.getAllocatedType();
4718 const Type *CastElTy = PTy->getElementType();
4719 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004720
4721 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4722 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4723 if (CastElTyAlign < AllocElTyAlign) return 0;
4724
Chris Lattner39387a52005-10-24 06:35:18 +00004725 // If the allocation has multiple uses, only promote it if we are strictly
4726 // increasing the alignment of the resultant allocation. If we keep it the
4727 // same, we open the door to infinite loops of various kinds.
4728 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4729
Chris Lattnerb3f83972005-10-24 06:03:58 +00004730 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4731 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004732 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004733
Chris Lattner455fcc82005-10-29 03:19:53 +00004734 // See if we can satisfy the modulus by pulling a scale out of the array
4735 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00004736 unsigned ArraySizeScale, ArrayOffset;
4737 Value *NumElements = // See if the array size is a decomposable linear expr.
4738 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4739
Chris Lattner455fcc82005-10-29 03:19:53 +00004740 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4741 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004742 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4743 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004744
Chris Lattner455fcc82005-10-29 03:19:53 +00004745 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4746 Value *Amt = 0;
4747 if (Scale == 1) {
4748 Amt = NumElements;
4749 } else {
4750 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4751 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4752 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4753 else if (Scale != 1) {
4754 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4755 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004756 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004757 }
4758
Chris Lattnercfd65102005-10-29 04:36:15 +00004759 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4760 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4761 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4762 Amt = InsertNewInstBefore(Tmp, AI);
4763 }
4764
Chris Lattnerb3f83972005-10-24 06:03:58 +00004765 std::string Name = AI.getName(); AI.setName("");
4766 AllocationInst *New;
4767 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004768 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004769 else
Nate Begeman14b05292005-11-05 09:21:28 +00004770 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004771 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004772
4773 // If the allocation has multiple uses, insert a cast and change all things
4774 // that used it to use the new cast. This will also hack on CI, but it will
4775 // die soon.
4776 if (!AI.hasOneUse()) {
4777 AddUsesToWorkList(AI);
4778 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4779 InsertNewInstBefore(NewCast, AI);
4780 AI.replaceAllUsesWith(NewCast);
4781 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004782 return ReplaceInstUsesWith(CI, New);
4783}
4784
Chris Lattner70074e02006-05-13 02:06:03 +00004785/// CanEvaluateInDifferentType - Return true if we can take the specified value
4786/// and return it without inserting any new casts. This is used by code that
4787/// tries to decide whether promoting or shrinking integer operations to wider
4788/// or smaller types will allow us to eliminate a truncate or extend.
4789static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
4790 int &NumCastsRemoved) {
4791 if (isa<Constant>(V)) return true;
4792
4793 Instruction *I = dyn_cast<Instruction>(V);
4794 if (!I || !I->hasOneUse()) return false;
4795
4796 switch (I->getOpcode()) {
4797 case Instruction::And:
4798 case Instruction::Or:
4799 case Instruction::Xor:
4800 // These operators can all arbitrarily be extended or truncated.
4801 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
4802 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
4803 case Instruction::Cast:
4804 // If this is a cast from the destination type, we can trivially eliminate
4805 // it, and this will remove a cast overall.
4806 if (I->getOperand(0)->getType() == Ty) {
4807 ++NumCastsRemoved;
4808 return true;
4809 }
4810 // TODO: Can handle more cases here.
4811 break;
4812 }
4813
4814 return false;
4815}
4816
4817/// EvaluateInDifferentType - Given an expression that
4818/// CanEvaluateInDifferentType returns true for, actually insert the code to
4819/// evaluate the expression.
4820Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
4821 if (Constant *C = dyn_cast<Constant>(V))
4822 return ConstantExpr::getCast(C, Ty);
4823
4824 // Otherwise, it must be an instruction.
4825 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00004826 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00004827 switch (I->getOpcode()) {
4828 case Instruction::And:
4829 case Instruction::Or:
4830 case Instruction::Xor: {
4831 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
4832 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
4833 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
4834 LHS, RHS, I->getName());
4835 break;
4836 }
4837 case Instruction::Cast:
4838 // If this is a cast from the destination type, return the input.
4839 if (I->getOperand(0)->getType() == Ty)
4840 return I->getOperand(0);
4841
4842 // TODO: Can handle more cases here.
4843 assert(0 && "Unreachable!");
4844 break;
4845 }
4846
4847 return InsertNewInstBefore(Res, *I);
4848}
4849
Chris Lattnerb3f83972005-10-24 06:03:58 +00004850
Chris Lattnera1be5662002-05-02 17:06:02 +00004851// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004852//
Chris Lattner7e708292002-06-25 16:13:24 +00004853Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004854 Value *Src = CI.getOperand(0);
4855
Chris Lattnera1be5662002-05-02 17:06:02 +00004856 // If the user is casting a value to the same type, eliminate this cast
4857 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00004858 if (CI.getType() == Src->getType())
4859 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00004860
Chris Lattnere87597f2004-10-16 18:11:37 +00004861 if (isa<UndefValue>(Src)) // cast undef -> undef
4862 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4863
Chris Lattnera1be5662002-05-02 17:06:02 +00004864 // If casting the result of another cast instruction, try to eliminate this
4865 // one!
4866 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00004867 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4868 Value *A = CSrc->getOperand(0);
4869 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4870 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004871 // This instruction now refers directly to the cast's src operand. This
4872 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00004873 CI.setOperand(0, CSrc->getOperand(0));
4874 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00004875 }
4876
Chris Lattner8fd217c2002-08-02 20:00:25 +00004877 // If this is an A->B->A cast, and we are dealing with integral types, try
4878 // to convert this into a logical 'and' instruction.
4879 //
Misha Brukmanfd939082005-04-21 23:48:37 +00004880 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00004881 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00004882 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00004883 CSrc->getType()->getPrimitiveSizeInBits() <
4884 CI.getType()->getPrimitiveSizeInBits()&&
4885 A->getType()->getPrimitiveSizeInBits() ==
4886 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00004887 assert(CSrc->getType() != Type::ULongTy &&
4888 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00004889 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner6e7ba452005-01-01 16:22:27 +00004890 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4891 AndValue);
4892 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4893 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4894 if (And->getType() != CI.getType()) {
4895 And->setName(CSrc->getName()+".mask");
4896 InsertNewInstBefore(And, CI);
4897 And = new CastInst(And, CI.getType());
4898 }
4899 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00004900 }
4901 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004902
Chris Lattnera710ddc2004-05-25 04:29:21 +00004903 // If this is a cast to bool, turn it into the appropriate setne instruction.
4904 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00004905 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00004906 Constant::getNullValue(CI.getOperand(0)->getType()));
4907
Chris Lattner6dce1a72006-02-07 06:56:34 +00004908 // See if we can simplify any instructions used by the LHS whose sole
4909 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00004910 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4911 uint64_t KnownZero, KnownOne;
4912 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4913 KnownZero, KnownOne))
4914 return &CI;
4915 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004916
Chris Lattner797249b2003-06-21 23:12:02 +00004917 // If casting the result of a getelementptr instruction with no offset, turn
4918 // this into a cast of the original pointer!
4919 //
Chris Lattner79d35b32003-06-23 21:59:52 +00004920 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00004921 bool AllZeroOperands = true;
4922 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4923 if (!isa<Constant>(GEP->getOperand(i)) ||
4924 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4925 AllZeroOperands = false;
4926 break;
4927 }
4928 if (AllZeroOperands) {
4929 CI.setOperand(0, GEP->getOperand(0));
4930 return &CI;
4931 }
4932 }
4933
Chris Lattnerbc61e662003-11-02 05:57:39 +00004934 // If we are casting a malloc or alloca to a pointer to a type of the same
4935 // size, rewrite the allocation instruction to allocate the "right" type.
4936 //
4937 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00004938 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4939 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004940
Chris Lattner6e7ba452005-01-01 16:22:27 +00004941 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4942 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4943 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00004944 if (isa<PHINode>(Src))
4945 if (Instruction *NV = FoldOpIntoPhi(CI))
4946 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00004947
4948 // If the source and destination are pointers, and this cast is equivalent to
4949 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4950 // This can enhance SROA and other transforms that want type-safe pointers.
4951 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4952 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4953 const Type *DstTy = DstPTy->getElementType();
4954 const Type *SrcTy = SrcPTy->getElementType();
4955
4956 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4957 unsigned NumZeros = 0;
4958 while (SrcTy != DstTy &&
4959 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4960 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4961 ++NumZeros;
4962 }
Chris Lattner4e998b22004-09-29 05:07:12 +00004963
Chris Lattner9fb92132006-04-12 18:09:35 +00004964 // If we found a path from the src to dest, create the getelementptr now.
4965 if (SrcTy == DstTy) {
4966 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4967 return new GetElementPtrInst(Src, Idxs);
4968 }
4969 }
4970
Chris Lattner24c8e382003-07-24 17:35:25 +00004971 // If the source value is an instruction with only this use, we can attempt to
4972 // propagate the cast into the instruction. Also, only handle integral types
4973 // for now.
Chris Lattner01575b72006-05-25 23:24:33 +00004974 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerfd059242003-10-15 16:48:29 +00004975 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00004976 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner70074e02006-05-13 02:06:03 +00004977
4978 int NumCastsRemoved = 0;
4979 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
4980 // If this cast is a truncate, evaluting in a different type always
4981 // eliminates the cast, so it is always a win. If this is a noop-cast
4982 // this just removes a noop cast which isn't pointful, but simplifies
4983 // the code. If this is a zero-extension, we need to do an AND to
4984 // maintain the clear top-part of the computation, so we require that
4985 // the input have eliminated at least one cast. If this is a sign
4986 // extension, we insert two new casts (to do the extension) so we
4987 // require that two casts have been eliminated.
4988 bool DoXForm;
4989 switch (getCastType(Src->getType(), CI.getType())) {
4990 default: assert(0 && "Unknown cast type!");
4991 case Noop:
4992 case Truncate:
4993 DoXForm = true;
4994 break;
4995 case Zeroext:
4996 DoXForm = NumCastsRemoved >= 1;
4997 break;
4998 case Signext:
4999 DoXForm = NumCastsRemoved >= 2;
5000 break;
5001 }
5002
5003 if (DoXForm) {
5004 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5005 assert(Res->getType() == CI.getType());
5006 switch (getCastType(Src->getType(), CI.getType())) {
5007 default: assert(0 && "Unknown cast type!");
5008 case Noop:
5009 case Truncate:
5010 // Just replace this cast with the result.
5011 return ReplaceInstUsesWith(CI, Res);
5012 case Zeroext: {
5013 // We need to emit an AND to clear the high bits.
5014 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5015 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5016 assert(SrcBitSize < DestBitSize && "Not a zext?");
5017 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5018 C = ConstantExpr::getCast(C, CI.getType());
5019 return BinaryOperator::createAnd(Res, C);
5020 }
5021 case Signext:
5022 // We need to emit a cast to truncate, then a cast to sext.
5023 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5024 CI.getType());
5025 }
5026 }
5027 }
5028
Chris Lattner24c8e382003-07-24 17:35:25 +00005029 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005030 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5031 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00005032
5033 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5034 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5035
5036 switch (SrcI->getOpcode()) {
5037 case Instruction::Add:
5038 case Instruction::Mul:
5039 case Instruction::And:
5040 case Instruction::Or:
5041 case Instruction::Xor:
5042 // If we are discarding information, or just changing the sign, rewrite.
5043 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5044 // Don't insert two casts if they cannot be eliminated. We allow two
5045 // casts to be inserted if the sizes are the same. This could only be
5046 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00005047 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5048 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00005049 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5050 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5051 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5052 ->getOpcode(), Op0c, Op1c);
5053 }
5054 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00005055
5056 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5057 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5058 Op1 == ConstantBool::True &&
5059 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5060 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5061 return BinaryOperator::createXor(New,
5062 ConstantInt::get(CI.getType(), 1));
5063 }
Chris Lattner24c8e382003-07-24 17:35:25 +00005064 break;
5065 case Instruction::Shl:
5066 // Allow changing the sign of the source operand. Do not allow changing
5067 // the size of the shift, UNLESS the shift amount is a constant. We
5068 // mush not change variable sized shifts to a smaller size, because it
5069 // is undefined to shift more bits out than exist in the value.
5070 if (DestBitSize == SrcBitSize ||
5071 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5072 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5073 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5074 }
5075 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00005076 case Instruction::Shr:
5077 // If this is a signed shr, and if all bits shifted in are about to be
5078 // truncated off, turn it into an unsigned shr to allow greater
5079 // simplifications.
5080 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5081 isa<ConstantInt>(Op1)) {
5082 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5083 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5084 // Convert to unsigned.
5085 Value *N1 = InsertOperandCastBefore(Op0,
5086 Op0->getType()->getUnsignedVersion(), &CI);
5087 // Insert the new shift, which is now unsigned.
5088 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5089 Op1, Src->getName()), CI);
5090 return new CastInst(N1, CI.getType());
5091 }
5092 }
5093 break;
5094
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005095 case Instruction::SetEQ:
Chris Lattner693787a2005-05-04 19:10:26 +00005096 case Instruction::SetNE:
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005097 // We if we are just checking for a seteq of a single bit and casting it
5098 // to an integer. If so, shift the bit to the appropriate place then
5099 // cast to integer to avoid the comparison.
Chris Lattner693787a2005-05-04 19:10:26 +00005100 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005101 uint64_t Op1CV = Op1C->getZExtValue();
5102 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5103 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5104 // cast (X == 1) to int --> X iff X has only the low bit set.
5105 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5106 // cast (X != 0) to int --> X iff X has only the low bit set.
5107 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5108 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5109 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5110 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5111 // If Op1C some other power of two, convert:
5112 uint64_t KnownZero, KnownOne;
5113 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5114 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5115
5116 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5117 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5118 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5119 // (X&4) == 2 --> false
5120 // (X&4) != 2 --> true
Chris Lattner06e1e252006-02-28 19:47:20 +00005121 Constant *Res = ConstantBool::get(isSetNE);
5122 Res = ConstantExpr::getCast(Res, CI.getType());
5123 return ReplaceInstUsesWith(CI, Res);
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005124 }
5125
5126 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5127 Value *In = Op0;
5128 if (ShiftAmt) {
Chris Lattnerd1523802005-05-06 01:53:19 +00005129 // Perform an unsigned shr by shiftamt. Convert input to
5130 // unsigned if it is signed.
Chris Lattnerd1523802005-05-06 01:53:19 +00005131 if (In->getType()->isSigned())
5132 In = InsertNewInstBefore(new CastInst(In,
5133 In->getType()->getUnsignedVersion(), In->getName()),CI);
5134 // Insert the shift to put the result in the low bit.
5135 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005136 ConstantInt::get(Type::UByteTy, ShiftAmt),
5137 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005138 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005139
5140 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5141 Constant *One = ConstantInt::get(In->getType(), 1);
5142 In = BinaryOperator::createXor(In, One, "tmp");
5143 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005144 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005145
5146 if (CI.getType() == In->getType())
5147 return ReplaceInstUsesWith(CI, In);
5148 else
5149 return new CastInst(In, CI.getType());
Chris Lattnerd1523802005-05-06 01:53:19 +00005150 }
Chris Lattner693787a2005-05-04 19:10:26 +00005151 }
5152 }
5153 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00005154 }
5155 }
Chris Lattner01575b72006-05-25 23:24:33 +00005156
5157 if (SrcI->hasOneUse()) {
5158 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5159 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5160 // because the inputs are known to be a vector. Check to see if this is
5161 // a cast to a vector with the same # elts.
5162 if (isa<PackedType>(CI.getType()) &&
5163 cast<PackedType>(CI.getType())->getNumElements() ==
5164 SVI->getType()->getNumElements()) {
5165 CastInst *Tmp;
5166 // If either of the operands is a cast from CI.getType(), then
5167 // evaluating the shuffle in the casted destination's type will allow
5168 // us to eliminate at least one cast.
5169 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5170 Tmp->getOperand(0)->getType() == CI.getType()) ||
5171 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner18a4af22006-06-06 22:26:02 +00005172 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner01575b72006-05-25 23:24:33 +00005173 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5174 CI.getType(), &CI);
5175 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5176 CI.getType(), &CI);
5177 // Return a new shuffle vector. Use the same element ID's, as we
5178 // know the vector types match #elts.
5179 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5180 }
5181 }
5182 }
5183 }
5184 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005185
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005186 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005187}
5188
Chris Lattnere576b912004-04-09 23:46:01 +00005189/// GetSelectFoldableOperands - We want to turn code that looks like this:
5190/// %C = or %A, %B
5191/// %D = select %cond, %C, %A
5192/// into:
5193/// %C = select %cond, %B, 0
5194/// %D = or %A, %C
5195///
5196/// Assuming that the specified instruction is an operand to the select, return
5197/// a bitmask indicating which operands of this instruction are foldable if they
5198/// equal the other incoming value of the select.
5199///
5200static unsigned GetSelectFoldableOperands(Instruction *I) {
5201 switch (I->getOpcode()) {
5202 case Instruction::Add:
5203 case Instruction::Mul:
5204 case Instruction::And:
5205 case Instruction::Or:
5206 case Instruction::Xor:
5207 return 3; // Can fold through either operand.
5208 case Instruction::Sub: // Can only fold on the amount subtracted.
5209 case Instruction::Shl: // Can only fold on the shift amount.
5210 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00005211 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00005212 default:
5213 return 0; // Cannot fold
5214 }
5215}
5216
5217/// GetSelectFoldableConstant - For the same transformation as the previous
5218/// function, return the identity constant that goes into the select.
5219static Constant *GetSelectFoldableConstant(Instruction *I) {
5220 switch (I->getOpcode()) {
5221 default: assert(0 && "This cannot happen!"); abort();
5222 case Instruction::Add:
5223 case Instruction::Sub:
5224 case Instruction::Or:
5225 case Instruction::Xor:
5226 return Constant::getNullValue(I->getType());
5227 case Instruction::Shl:
5228 case Instruction::Shr:
5229 return Constant::getNullValue(Type::UByteTy);
5230 case Instruction::And:
5231 return ConstantInt::getAllOnesValue(I->getType());
5232 case Instruction::Mul:
5233 return ConstantInt::get(I->getType(), 1);
5234 }
5235}
5236
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005237/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5238/// have the same opcode and only one use each. Try to simplify this.
5239Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5240 Instruction *FI) {
5241 if (TI->getNumOperands() == 1) {
5242 // If this is a non-volatile load or a cast from the same type,
5243 // merge.
5244 if (TI->getOpcode() == Instruction::Cast) {
5245 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5246 return 0;
5247 } else {
5248 return 0; // unknown unary op.
5249 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005250
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005251 // Fold this by inserting a select from the input values.
5252 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5253 FI->getOperand(0), SI.getName()+".v");
5254 InsertNewInstBefore(NewSI, SI);
5255 return new CastInst(NewSI, TI->getType());
5256 }
5257
5258 // Only handle binary operators here.
5259 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5260 return 0;
5261
5262 // Figure out if the operations have any operands in common.
5263 Value *MatchOp, *OtherOpT, *OtherOpF;
5264 bool MatchIsOpZero;
5265 if (TI->getOperand(0) == FI->getOperand(0)) {
5266 MatchOp = TI->getOperand(0);
5267 OtherOpT = TI->getOperand(1);
5268 OtherOpF = FI->getOperand(1);
5269 MatchIsOpZero = true;
5270 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5271 MatchOp = TI->getOperand(1);
5272 OtherOpT = TI->getOperand(0);
5273 OtherOpF = FI->getOperand(0);
5274 MatchIsOpZero = false;
5275 } else if (!TI->isCommutative()) {
5276 return 0;
5277 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5278 MatchOp = TI->getOperand(0);
5279 OtherOpT = TI->getOperand(1);
5280 OtherOpF = FI->getOperand(0);
5281 MatchIsOpZero = true;
5282 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5283 MatchOp = TI->getOperand(1);
5284 OtherOpT = TI->getOperand(0);
5285 OtherOpF = FI->getOperand(1);
5286 MatchIsOpZero = true;
5287 } else {
5288 return 0;
5289 }
5290
5291 // If we reach here, they do have operations in common.
5292 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5293 OtherOpF, SI.getName()+".v");
5294 InsertNewInstBefore(NewSI, SI);
5295
5296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5297 if (MatchIsOpZero)
5298 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5299 else
5300 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5301 } else {
5302 if (MatchIsOpZero)
5303 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5304 else
5305 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5306 }
5307}
5308
Chris Lattner3d69f462004-03-12 05:52:32 +00005309Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005310 Value *CondVal = SI.getCondition();
5311 Value *TrueVal = SI.getTrueValue();
5312 Value *FalseVal = SI.getFalseValue();
5313
5314 // select true, X, Y -> X
5315 // select false, X, Y -> Y
5316 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00005317 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005318 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005319 else {
5320 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005321 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005322 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005323
5324 // select C, X, X -> X
5325 if (TrueVal == FalseVal)
5326 return ReplaceInstUsesWith(SI, TrueVal);
5327
Chris Lattnere87597f2004-10-16 18:11:37 +00005328 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5329 return ReplaceInstUsesWith(SI, FalseVal);
5330 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5331 return ReplaceInstUsesWith(SI, TrueVal);
5332 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5333 if (isa<Constant>(TrueVal))
5334 return ReplaceInstUsesWith(SI, TrueVal);
5335 else
5336 return ReplaceInstUsesWith(SI, FalseVal);
5337 }
5338
Chris Lattner0c199a72004-04-08 04:43:23 +00005339 if (SI.getType() == Type::BoolTy)
5340 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5341 if (C == ConstantBool::True) {
5342 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005343 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005344 } else {
5345 // Change: A = select B, false, C --> A = and !B, C
5346 Value *NotCond =
5347 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5348 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005349 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005350 }
5351 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5352 if (C == ConstantBool::False) {
5353 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005354 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005355 } else {
5356 // Change: A = select B, C, true --> A = or !B, C
5357 Value *NotCond =
5358 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5359 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005360 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005361 }
5362 }
5363
Chris Lattner2eefe512004-04-09 19:05:30 +00005364 // Selecting between two integer constants?
5365 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5366 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5367 // select C, 1, 0 -> cast C to int
5368 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5369 return new CastInst(CondVal, SI.getType());
5370 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5371 // select C, 0, 1 -> cast !C to int
5372 Value *NotCond =
5373 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00005374 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00005375 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00005376 }
Chris Lattner457dd822004-06-09 07:59:58 +00005377
5378 // If one of the constants is zero (we know they can't both be) and we
5379 // have a setcc instruction with zero, and we have an 'and' with the
5380 // non-constant value, eliminate this whole mess. This corresponds to
5381 // cases like this: ((X & 27) ? 27 : 0)
5382 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5383 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5384 if ((IC->getOpcode() == Instruction::SetEQ ||
5385 IC->getOpcode() == Instruction::SetNE) &&
5386 isa<ConstantInt>(IC->getOperand(1)) &&
5387 cast<Constant>(IC->getOperand(1))->isNullValue())
5388 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5389 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005390 isa<ConstantInt>(ICA->getOperand(1)) &&
5391 (ICA->getOperand(1) == TrueValC ||
5392 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00005393 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5394 // Okay, now we know that everything is set up, we just don't
5395 // know whether we have a setne or seteq and whether the true or
5396 // false val is the zero.
5397 bool ShouldNotVal = !TrueValC->isNullValue();
5398 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5399 Value *V = ICA;
5400 if (ShouldNotVal)
5401 V = InsertNewInstBefore(BinaryOperator::create(
5402 Instruction::Xor, V, ICA->getOperand(1)), SI);
5403 return ReplaceInstUsesWith(SI, V);
5404 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005405 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005406
5407 // See if we are selecting two values based on a comparison of the two values.
5408 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5409 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5410 // Transform (X == Y) ? X : Y -> Y
5411 if (SCI->getOpcode() == Instruction::SetEQ)
5412 return ReplaceInstUsesWith(SI, FalseVal);
5413 // Transform (X != Y) ? X : Y -> X
5414 if (SCI->getOpcode() == Instruction::SetNE)
5415 return ReplaceInstUsesWith(SI, TrueVal);
5416 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5417
5418 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5419 // Transform (X == Y) ? Y : X -> X
5420 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00005421 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005422 // Transform (X != Y) ? Y : X -> Y
5423 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00005424 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005425 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5426 }
5427 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005428
Chris Lattner87875da2005-01-13 22:52:24 +00005429 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5430 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5431 if (TI->hasOneUse() && FI->hasOneUse()) {
5432 bool isInverse = false;
5433 Instruction *AddOp = 0, *SubOp = 0;
5434
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005435 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5436 if (TI->getOpcode() == FI->getOpcode())
5437 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5438 return IV;
5439
5440 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5441 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00005442 if (TI->getOpcode() == Instruction::Sub &&
5443 FI->getOpcode() == Instruction::Add) {
5444 AddOp = FI; SubOp = TI;
5445 } else if (FI->getOpcode() == Instruction::Sub &&
5446 TI->getOpcode() == Instruction::Add) {
5447 AddOp = TI; SubOp = FI;
5448 }
5449
5450 if (AddOp) {
5451 Value *OtherAddOp = 0;
5452 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5453 OtherAddOp = AddOp->getOperand(1);
5454 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5455 OtherAddOp = AddOp->getOperand(0);
5456 }
5457
5458 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00005459 // So at this point we know we have (Y -> OtherAddOp):
5460 // select C, (add X, Y), (sub X, Z)
5461 Value *NegVal; // Compute -Z
5462 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5463 NegVal = ConstantExpr::getNeg(C);
5464 } else {
5465 NegVal = InsertNewInstBefore(
5466 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00005467 }
Chris Lattner97f37a42006-02-24 18:05:58 +00005468
5469 Value *NewTrueOp = OtherAddOp;
5470 Value *NewFalseOp = NegVal;
5471 if (AddOp != TI)
5472 std::swap(NewTrueOp, NewFalseOp);
5473 Instruction *NewSel =
5474 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5475
5476 NewSel = InsertNewInstBefore(NewSel, SI);
5477 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00005478 }
5479 }
5480 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005481
Chris Lattnere576b912004-04-09 23:46:01 +00005482 // See if we can fold the select into one of our operands.
5483 if (SI.getType()->isInteger()) {
5484 // See the comment above GetSelectFoldableOperands for a description of the
5485 // transformation we are doing here.
5486 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5487 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5488 !isa<Constant>(FalseVal))
5489 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5490 unsigned OpToFold = 0;
5491 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5492 OpToFold = 1;
5493 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5494 OpToFold = 2;
5495 }
5496
5497 if (OpToFold) {
5498 Constant *C = GetSelectFoldableConstant(TVI);
5499 std::string Name = TVI->getName(); TVI->setName("");
5500 Instruction *NewSel =
5501 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5502 Name);
5503 InsertNewInstBefore(NewSel, SI);
5504 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5505 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5506 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5507 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5508 else {
5509 assert(0 && "Unknown instruction!!");
5510 }
5511 }
5512 }
Chris Lattnera96879a2004-09-29 17:40:11 +00005513
Chris Lattnere576b912004-04-09 23:46:01 +00005514 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5515 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5516 !isa<Constant>(TrueVal))
5517 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5518 unsigned OpToFold = 0;
5519 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5520 OpToFold = 1;
5521 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5522 OpToFold = 2;
5523 }
5524
5525 if (OpToFold) {
5526 Constant *C = GetSelectFoldableConstant(FVI);
5527 std::string Name = FVI->getName(); FVI->setName("");
5528 Instruction *NewSel =
5529 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5530 Name);
5531 InsertNewInstBefore(NewSel, SI);
5532 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5533 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5534 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5535 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5536 else {
5537 assert(0 && "Unknown instruction!!");
5538 }
5539 }
5540 }
5541 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00005542
5543 if (BinaryOperator::isNot(CondVal)) {
5544 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5545 SI.setOperand(1, FalseVal);
5546 SI.setOperand(2, TrueVal);
5547 return &SI;
5548 }
5549
Chris Lattner3d69f462004-03-12 05:52:32 +00005550 return 0;
5551}
5552
Chris Lattner95a959d2006-03-06 20:18:44 +00005553/// GetKnownAlignment - If the specified pointer has an alignment that we can
5554/// determine, return it, otherwise return 0.
5555static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5556 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5557 unsigned Align = GV->getAlignment();
5558 if (Align == 0 && TD)
5559 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5560 return Align;
5561 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5562 unsigned Align = AI->getAlignment();
5563 if (Align == 0 && TD) {
5564 if (isa<AllocaInst>(AI))
5565 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5566 else if (isa<MallocInst>(AI)) {
5567 // Malloc returns maximally aligned memory.
5568 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5569 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5570 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5571 }
5572 }
5573 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00005574 } else if (isa<CastInst>(V) ||
5575 (isa<ConstantExpr>(V) &&
5576 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5577 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005578 if (isa<PointerType>(CI->getOperand(0)->getType()))
5579 return GetKnownAlignment(CI->getOperand(0), TD);
5580 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00005581 } else if (isa<GetElementPtrInst>(V) ||
5582 (isa<ConstantExpr>(V) &&
5583 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5584 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005585 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5586 if (BaseAlignment == 0) return 0;
5587
5588 // If all indexes are zero, it is just the alignment of the base pointer.
5589 bool AllZeroOperands = true;
5590 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5591 if (!isa<Constant>(GEPI->getOperand(i)) ||
5592 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5593 AllZeroOperands = false;
5594 break;
5595 }
5596 if (AllZeroOperands)
5597 return BaseAlignment;
5598
5599 // Otherwise, if the base alignment is >= the alignment we expect for the
5600 // base pointer type, then we know that the resultant pointer is aligned at
5601 // least as much as its type requires.
5602 if (!TD) return 0;
5603
5604 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5605 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00005606 <= BaseAlignment) {
5607 const Type *GEPTy = GEPI->getType();
5608 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5609 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005610 return 0;
5611 }
5612 return 0;
5613}
5614
Chris Lattner3d69f462004-03-12 05:52:32 +00005615
Chris Lattner8b0ea312006-01-13 20:11:04 +00005616/// visitCallInst - CallInst simplification. This mostly only handles folding
5617/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5618/// the heavy lifting.
5619///
Chris Lattner9fe38862003-06-19 17:00:31 +00005620Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00005621 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5622 if (!II) return visitCallSite(&CI);
5623
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005624 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5625 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00005626 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005627 bool Changed = false;
5628
5629 // memmove/cpy/set of zero bytes is a noop.
5630 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5631 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5632
Chris Lattner35b9e482004-10-12 04:52:52 +00005633 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5634 if (CI->getRawValue() == 1) {
5635 // Replace the instruction with just byte operations. We would
5636 // transform other cases to loads/stores, but we don't know if
5637 // alignment is sufficient.
5638 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005639 }
5640
Chris Lattner35b9e482004-10-12 04:52:52 +00005641 // If we have a memmove and the source operation is a constant global,
5642 // then the source and dest pointers can't alias, so we can change this
5643 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00005644 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005645 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5646 if (GVSrc->isConstant()) {
5647 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00005648 const char *Name;
5649 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5650 Type::UIntTy)
5651 Name = "llvm.memcpy.i32";
5652 else
5653 Name = "llvm.memcpy.i64";
5654 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00005655 CI.getCalledFunction()->getFunctionType());
5656 CI.setOperand(0, MemCpy);
5657 Changed = true;
5658 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005659 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005660
Chris Lattner95a959d2006-03-06 20:18:44 +00005661 // If we can determine a pointer alignment that is bigger than currently
5662 // set, update the alignment.
5663 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5664 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5665 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5666 unsigned Align = std::min(Alignment1, Alignment2);
5667 if (MI->getAlignment()->getRawValue() < Align) {
5668 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5669 Changed = true;
5670 }
5671 } else if (isa<MemSetInst>(MI)) {
5672 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5673 if (MI->getAlignment()->getRawValue() < Alignment) {
5674 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5675 Changed = true;
5676 }
5677 }
5678
Chris Lattner8b0ea312006-01-13 20:11:04 +00005679 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00005680 } else {
5681 switch (II->getIntrinsicID()) {
5682 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00005683 case Intrinsic::ppc_altivec_lvx:
5684 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005685 case Intrinsic::x86_sse_loadu_ps:
5686 case Intrinsic::x86_sse2_loadu_pd:
5687 case Intrinsic::x86_sse2_loadu_dq:
5688 // Turn PPC lvx -> load if the pointer is known aligned.
5689 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00005690 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005691 Value *Ptr = InsertCastBefore(II->getOperand(1),
5692 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005693 return new LoadInst(Ptr);
5694 }
5695 break;
5696 case Intrinsic::ppc_altivec_stvx:
5697 case Intrinsic::ppc_altivec_stvxl:
5698 // Turn stvx -> store if the pointer is known aligned.
5699 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005700 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5701 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005702 return new StoreInst(II->getOperand(1), Ptr);
5703 }
5704 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005705 case Intrinsic::x86_sse_storeu_ps:
5706 case Intrinsic::x86_sse2_storeu_pd:
5707 case Intrinsic::x86_sse2_storeu_dq:
5708 case Intrinsic::x86_sse2_storel_dq:
5709 // Turn X86 storeu -> store if the pointer is known aligned.
5710 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5711 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5712 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5713 return new StoreInst(II->getOperand(2), Ptr);
5714 }
5715 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00005716 case Intrinsic::ppc_altivec_vperm:
5717 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5718 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5719 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5720
5721 // Check that all of the elements are integer constants or undefs.
5722 bool AllEltsOk = true;
5723 for (unsigned i = 0; i != 16; ++i) {
5724 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5725 !isa<UndefValue>(Mask->getOperand(i))) {
5726 AllEltsOk = false;
5727 break;
5728 }
5729 }
5730
5731 if (AllEltsOk) {
5732 // Cast the input vectors to byte vectors.
5733 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5734 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5735 Value *Result = UndefValue::get(Op0->getType());
5736
5737 // Only extract each element once.
5738 Value *ExtractedElts[32];
5739 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5740
5741 for (unsigned i = 0; i != 16; ++i) {
5742 if (isa<UndefValue>(Mask->getOperand(i)))
5743 continue;
5744 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5745 Idx &= 31; // Match the hardware behavior.
5746
5747 if (ExtractedElts[Idx] == 0) {
5748 Instruction *Elt =
5749 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5750 ConstantUInt::get(Type::UIntTy, Idx&15),
5751 "tmp");
5752 InsertNewInstBefore(Elt, CI);
5753 ExtractedElts[Idx] = Elt;
5754 }
5755
5756 // Insert this value into the result vector.
5757 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5758 ConstantUInt::get(Type::UIntTy, i),
5759 "tmp");
5760 InsertNewInstBefore(cast<Instruction>(Result), CI);
5761 }
5762 return new CastInst(Result, CI.getType());
5763 }
5764 }
5765 break;
5766
Chris Lattnera728ddc2006-01-13 21:28:09 +00005767 case Intrinsic::stackrestore: {
5768 // If the save is right next to the restore, remove the restore. This can
5769 // happen when variable allocas are DCE'd.
5770 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5771 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5772 BasicBlock::iterator BI = SS;
5773 if (&*++BI == II)
5774 return EraseInstFromFunction(CI);
5775 }
5776 }
5777
5778 // If the stack restore is in a return/unwind block and if there are no
5779 // allocas or calls between the restore and the return, nuke the restore.
5780 TerminatorInst *TI = II->getParent()->getTerminator();
5781 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5782 BasicBlock::iterator BI = II;
5783 bool CannotRemove = false;
5784 for (++BI; &*BI != TI; ++BI) {
5785 if (isa<AllocaInst>(BI) ||
5786 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5787 CannotRemove = true;
5788 break;
5789 }
5790 }
5791 if (!CannotRemove)
5792 return EraseInstFromFunction(CI);
5793 }
5794 break;
5795 }
5796 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005797 }
5798
Chris Lattner8b0ea312006-01-13 20:11:04 +00005799 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005800}
5801
5802// InvokeInst simplification
5803//
5804Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00005805 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005806}
5807
Chris Lattnera44d8a22003-10-07 22:32:43 +00005808// visitCallSite - Improvements for call and invoke instructions.
5809//
5810Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00005811 bool Changed = false;
5812
5813 // If the callee is a constexpr cast of a function, attempt to move the cast
5814 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00005815 if (transformConstExprCastCall(CS)) return 0;
5816
Chris Lattner6c266db2003-10-07 22:54:13 +00005817 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00005818
Chris Lattner08b22ec2005-05-13 07:09:09 +00005819 if (Function *CalleeF = dyn_cast<Function>(Callee))
5820 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5821 Instruction *OldCall = CS.getInstruction();
5822 // If the call and callee calling conventions don't match, this call must
5823 // be unreachable, as the call is undefined.
5824 new StoreInst(ConstantBool::True,
5825 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5826 if (!OldCall->use_empty())
5827 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5828 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5829 return EraseInstFromFunction(*OldCall);
5830 return 0;
5831 }
5832
Chris Lattner17be6352004-10-18 02:59:09 +00005833 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5834 // This instruction is not reachable, just remove it. We insert a store to
5835 // undef so that we know that this code is not reachable, despite the fact
5836 // that we can't modify the CFG here.
5837 new StoreInst(ConstantBool::True,
5838 UndefValue::get(PointerType::get(Type::BoolTy)),
5839 CS.getInstruction());
5840
5841 if (!CS.getInstruction()->use_empty())
5842 CS.getInstruction()->
5843 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5844
5845 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5846 // Don't break the CFG, insert a dummy cond branch.
5847 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5848 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00005849 }
Chris Lattner17be6352004-10-18 02:59:09 +00005850 return EraseInstFromFunction(*CS.getInstruction());
5851 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005852
Chris Lattner6c266db2003-10-07 22:54:13 +00005853 const PointerType *PTy = cast<PointerType>(Callee->getType());
5854 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5855 if (FTy->isVarArg()) {
5856 // See if we can optimize any arguments passed through the varargs area of
5857 // the call.
5858 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5859 E = CS.arg_end(); I != E; ++I)
5860 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5861 // If this cast does not effect the value passed through the varargs
5862 // area, we can eliminate the use of the cast.
5863 Value *Op = CI->getOperand(0);
5864 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5865 *I = Op;
5866 Changed = true;
5867 }
5868 }
5869 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005870
Chris Lattner6c266db2003-10-07 22:54:13 +00005871 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00005872}
5873
Chris Lattner9fe38862003-06-19 17:00:31 +00005874// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5875// attempt to move the cast to the arguments of the call/invoke.
5876//
5877bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5878 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5879 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00005880 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00005881 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00005882 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00005883 Instruction *Caller = CS.getInstruction();
5884
5885 // Okay, this is a cast from a function to a different type. Unless doing so
5886 // would cause a type conversion of one of our arguments, change this call to
5887 // be a direct call with arguments casted to the appropriate types.
5888 //
5889 const FunctionType *FT = Callee->getFunctionType();
5890 const Type *OldRetTy = Caller->getType();
5891
Chris Lattnerf78616b2004-01-14 06:06:08 +00005892 // Check to see if we are changing the return type...
5893 if (OldRetTy != FT->getReturnType()) {
5894 if (Callee->isExternal() &&
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00005895 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5896 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharth7a31b972006-04-20 15:41:37 +00005897 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00005898 && !Caller->use_empty())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005899 return false; // Cannot transform this return value...
5900
5901 // If the callsite is an invoke instruction, and the return value is used by
5902 // a PHI node in a successor, we cannot change the return type of the call
5903 // because there is no place to put the cast instruction (without breaking
5904 // the critical edge). Bail out in this case.
5905 if (!Caller->use_empty())
5906 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5907 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5908 UI != E; ++UI)
5909 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5910 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005911 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005912 return false;
5913 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005914
5915 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5916 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005917
Chris Lattner9fe38862003-06-19 17:00:31 +00005918 CallSite::arg_iterator AI = CS.arg_begin();
5919 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5920 const Type *ParamTy = FT->getParamType(i);
5921 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00005922 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005923 }
5924
5925 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5926 Callee->isExternal())
5927 return false; // Do not delete arguments unless we have a function body...
5928
5929 // Okay, we decided that this is a safe thing to do: go ahead and start
5930 // inserting cast instructions as necessary...
5931 std::vector<Value*> Args;
5932 Args.reserve(NumActualArgs);
5933
5934 AI = CS.arg_begin();
5935 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5936 const Type *ParamTy = FT->getParamType(i);
5937 if ((*AI)->getType() == ParamTy) {
5938 Args.push_back(*AI);
5939 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00005940 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5941 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00005942 }
5943 }
5944
5945 // If the function takes more arguments than the call was taking, add them
5946 // now...
5947 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5948 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5949
5950 // If we are removing arguments to the function, emit an obnoxious warning...
5951 if (FT->getNumParams() < NumActualArgs)
5952 if (!FT->isVarArg()) {
5953 std::cerr << "WARNING: While resolving call to function '"
5954 << Callee->getName() << "' arguments were dropped!\n";
5955 } else {
5956 // Add all of the arguments in their promoted form to the arg list...
5957 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5958 const Type *PTy = getPromotedType((*AI)->getType());
5959 if (PTy != (*AI)->getType()) {
5960 // Must promote to pass through va_arg area!
5961 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5962 InsertNewInstBefore(Cast, *Caller);
5963 Args.push_back(Cast);
5964 } else {
5965 Args.push_back(*AI);
5966 }
5967 }
5968 }
5969
5970 if (FT->getReturnType() == Type::VoidTy)
5971 Caller->setName(""); // Void type should not have a name...
5972
5973 Instruction *NC;
5974 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005975 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00005976 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00005977 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005978 } else {
5979 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00005980 if (cast<CallInst>(Caller)->isTailCall())
5981 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00005982 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005983 }
5984
5985 // Insert a cast of the return type as necessary...
5986 Value *NV = NC;
5987 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5988 if (NV->getType() != Type::VoidTy) {
5989 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00005990
5991 // If this is an invoke instruction, we should insert it after the first
5992 // non-phi, instruction in the normal successor block.
5993 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5994 BasicBlock::iterator I = II->getNormalDest()->begin();
5995 while (isa<PHINode>(I)) ++I;
5996 InsertNewInstBefore(NC, *I);
5997 } else {
5998 // Otherwise, it's a call, just insert cast right after the call instr
5999 InsertNewInstBefore(NC, *Caller);
6000 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006001 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00006002 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00006003 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00006004 }
6005 }
6006
6007 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6008 Caller->replaceAllUsesWith(NV);
6009 Caller->getParent()->getInstList().erase(Caller);
6010 removeFromWorkList(Caller);
6011 return true;
6012}
6013
6014
Chris Lattnerbac32862004-11-14 19:13:23 +00006015// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6016// operator and they all are only used by the PHI, PHI together their
6017// inputs, and do the operation once, to the result of the PHI.
6018Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6019 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6020
6021 // Scan the instruction, looking for input operations that can be folded away.
6022 // If all input operands to the phi are the same instruction (e.g. a cast from
6023 // the same type or "+42") we can pull the operation through the PHI, reducing
6024 // code size and simplifying code.
6025 Constant *ConstantOp = 0;
6026 const Type *CastSrcTy = 0;
6027 if (isa<CastInst>(FirstInst)) {
6028 CastSrcTy = FirstInst->getOperand(0)->getType();
6029 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6030 // Can fold binop or shift if the RHS is a constant.
6031 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6032 if (ConstantOp == 0) return 0;
6033 } else {
6034 return 0; // Cannot fold this operation.
6035 }
6036
6037 // Check to see if all arguments are the same operation.
6038 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6039 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6040 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6041 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6042 return 0;
6043 if (CastSrcTy) {
6044 if (I->getOperand(0)->getType() != CastSrcTy)
6045 return 0; // Cast operation must match.
6046 } else if (I->getOperand(1) != ConstantOp) {
6047 return 0;
6048 }
6049 }
6050
6051 // Okay, they are all the same operation. Create a new PHI node of the
6052 // correct type, and PHI together all of the LHS's of the instructions.
6053 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6054 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00006055 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00006056
6057 Value *InVal = FirstInst->getOperand(0);
6058 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00006059
6060 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00006061 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6062 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6063 if (NewInVal != InVal)
6064 InVal = 0;
6065 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6066 }
6067
6068 Value *PhiVal;
6069 if (InVal) {
6070 // The new PHI unions all of the same values together. This is really
6071 // common, so we handle it intelligently here for compile-time speed.
6072 PhiVal = InVal;
6073 delete NewPN;
6074 } else {
6075 InsertNewInstBefore(NewPN, PN);
6076 PhiVal = NewPN;
6077 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006078
Chris Lattnerbac32862004-11-14 19:13:23 +00006079 // Insert and return the new operation.
6080 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006081 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00006082 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006083 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006084 else
6085 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00006086 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006087}
Chris Lattnera1be5662002-05-02 17:06:02 +00006088
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006089/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6090/// that is dead.
6091static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6092 if (PN->use_empty()) return true;
6093 if (!PN->hasOneUse()) return false;
6094
6095 // Remember this node, and if we find the cycle, return.
6096 if (!PotentiallyDeadPHIs.insert(PN).second)
6097 return true;
6098
6099 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6100 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006101
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006102 return false;
6103}
6104
Chris Lattner473945d2002-05-06 18:06:38 +00006105// PHINode simplification
6106//
Chris Lattner7e708292002-06-25 16:13:24 +00006107Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00006108 if (Value *V = PN.hasConstantValue())
6109 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00006110
6111 // If the only user of this instruction is a cast instruction, and all of the
6112 // incoming values are constants, change this PHI to merge together the casted
6113 // constants.
6114 if (PN.hasOneUse())
6115 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6116 if (CI->getType() != PN.getType()) { // noop casts will be folded
6117 bool AllConstant = true;
6118 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6119 if (!isa<Constant>(PN.getIncomingValue(i))) {
6120 AllConstant = false;
6121 break;
6122 }
6123 if (AllConstant) {
6124 // Make a new PHI with all casted values.
6125 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6126 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6127 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6128 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6129 PN.getIncomingBlock(i));
6130 }
6131
6132 // Update the cast instruction.
6133 CI->setOperand(0, New);
6134 WorkList.push_back(CI); // revisit the cast instruction to fold.
6135 WorkList.push_back(New); // Make sure to revisit the new Phi
6136 return &PN; // PN is now dead!
6137 }
6138 }
Chris Lattnerbac32862004-11-14 19:13:23 +00006139
6140 // If all PHI operands are the same operation, pull them through the PHI,
6141 // reducing code size.
6142 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6143 PN.getIncomingValue(0)->hasOneUse())
6144 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6145 return Result;
6146
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006147 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6148 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6149 // PHI)... break the cycle.
6150 if (PN.hasOneUse())
6151 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6152 std::set<PHINode*> PotentiallyDeadPHIs;
6153 PotentiallyDeadPHIs.insert(&PN);
6154 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6155 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6156 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006157
Chris Lattner60921c92003-12-19 05:58:40 +00006158 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00006159}
6160
Chris Lattner28977af2004-04-05 01:30:19 +00006161static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6162 Instruction *InsertPoint,
6163 InstCombiner *IC) {
6164 unsigned PS = IC->getTargetData().getPointerSize();
6165 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00006166 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6167 // We must insert a cast to ensure we sign-extend.
6168 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6169 V->getName()), *InsertPoint);
6170 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6171 *InsertPoint);
6172}
6173
Chris Lattnera1be5662002-05-02 17:06:02 +00006174
Chris Lattner7e708292002-06-25 16:13:24 +00006175Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00006176 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00006177 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00006178 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006179 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00006180 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006181
Chris Lattnere87597f2004-10-16 18:11:37 +00006182 if (isa<UndefValue>(GEP.getOperand(0)))
6183 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6184
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006185 bool HasZeroPointerIndex = false;
6186 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6187 HasZeroPointerIndex = C->isNullValue();
6188
6189 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00006190 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00006191
Chris Lattner28977af2004-04-05 01:30:19 +00006192 // Eliminate unneeded casts for indices.
6193 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006194 gep_type_iterator GTI = gep_type_begin(GEP);
6195 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6196 if (isa<SequentialType>(*GTI)) {
6197 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6198 Value *Src = CI->getOperand(0);
6199 const Type *SrcTy = Src->getType();
6200 const Type *DestTy = CI->getType();
6201 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006202 if (SrcTy->getPrimitiveSizeInBits() ==
6203 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006204 // We can always eliminate a cast from ulong or long to the other.
6205 // We can always eliminate a cast from uint to int or the other on
6206 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00006207 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006208 MadeChange = true;
6209 GEP.setOperand(i, Src);
6210 }
6211 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6212 SrcTy->getPrimitiveSize() == 4) {
6213 // We can always eliminate a cast from int to [u]long. We can
6214 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6215 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00006216 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00006217 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006218 MadeChange = true;
6219 GEP.setOperand(i, Src);
6220 }
Chris Lattner28977af2004-04-05 01:30:19 +00006221 }
6222 }
6223 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006224 // If we are using a wider index than needed for this platform, shrink it
6225 // to what we need. If the incoming value needs a cast instruction,
6226 // insert it. This explicit cast can make subsequent optimizations more
6227 // obvious.
6228 Value *Op = GEP.getOperand(i);
6229 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00006230 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00006231 GEP.setOperand(i, ConstantExpr::getCast(C,
6232 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00006233 MadeChange = true;
6234 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006235 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6236 Op->getName()), GEP);
6237 GEP.setOperand(i, Op);
6238 MadeChange = true;
6239 }
Chris Lattner67769e52004-07-20 01:48:15 +00006240
6241 // If this is a constant idx, make sure to canonicalize it to be a signed
6242 // operand, otherwise CSE and other optimizations are pessimized.
6243 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6244 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6245 CUI->getType()->getSignedVersion()));
6246 MadeChange = true;
6247 }
Chris Lattner28977af2004-04-05 01:30:19 +00006248 }
6249 if (MadeChange) return &GEP;
6250
Chris Lattner90ac28c2002-08-02 19:29:35 +00006251 // Combine Indices - If the source pointer to this getelementptr instruction
6252 // is a getelementptr instruction, combine the indices of the two
6253 // getelementptr instructions into a single instruction.
6254 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00006255 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00006256 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00006257 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00006258
6259 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00006260 // Note that if our source is a gep chain itself that we wait for that
6261 // chain to be resolved before we perform this transformation. This
6262 // avoids us creating a TON of code in some cases.
6263 //
6264 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6265 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6266 return 0; // Wait until our source is folded to completion.
6267
Chris Lattner90ac28c2002-08-02 19:29:35 +00006268 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00006269
6270 // Find out whether the last index in the source GEP is a sequential idx.
6271 bool EndsWithSequential = false;
6272 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6273 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00006274 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00006275
Chris Lattner90ac28c2002-08-02 19:29:35 +00006276 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00006277 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00006278 // Replace: gep (gep %P, long B), long A, ...
6279 // With: T = long A+B; gep %P, T, ...
6280 //
Chris Lattner620ce142004-05-07 22:09:22 +00006281 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00006282 if (SO1 == Constant::getNullValue(SO1->getType())) {
6283 Sum = GO1;
6284 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6285 Sum = SO1;
6286 } else {
6287 // If they aren't the same type, convert both to an integer of the
6288 // target's pointer size.
6289 if (SO1->getType() != GO1->getType()) {
6290 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6291 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6292 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6293 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6294 } else {
6295 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00006296 if (SO1->getType()->getPrimitiveSize() == PS) {
6297 // Convert GO1 to SO1's type.
6298 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6299
6300 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6301 // Convert SO1 to GO1's type.
6302 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6303 } else {
6304 const Type *PT = TD->getIntPtrType();
6305 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6306 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6307 }
6308 }
6309 }
Chris Lattner620ce142004-05-07 22:09:22 +00006310 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6311 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6312 else {
Chris Lattner48595f12004-06-10 02:07:29 +00006313 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6314 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00006315 }
Chris Lattner28977af2004-04-05 01:30:19 +00006316 }
Chris Lattner620ce142004-05-07 22:09:22 +00006317
6318 // Recycle the GEP we already have if possible.
6319 if (SrcGEPOperands.size() == 2) {
6320 GEP.setOperand(0, SrcGEPOperands[0]);
6321 GEP.setOperand(1, Sum);
6322 return &GEP;
6323 } else {
6324 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6325 SrcGEPOperands.end()-1);
6326 Indices.push_back(Sum);
6327 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6328 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006329 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00006330 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006331 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00006332 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00006333 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6334 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00006335 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6336 }
6337
6338 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00006339 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00006340
Chris Lattner620ce142004-05-07 22:09:22 +00006341 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00006342 // GEP of global variable. If all of the indices for this GEP are
6343 // constants, we can promote this to a constexpr instead of an instruction.
6344
6345 // Scan for nonconstants...
6346 std::vector<Constant*> Indices;
6347 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6348 for (; I != E && isa<Constant>(*I); ++I)
6349 Indices.push_back(cast<Constant>(*I));
6350
6351 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00006352 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00006353
6354 // Replace all uses of the GEP with the new constexpr...
6355 return ReplaceInstUsesWith(GEP, CE);
6356 }
Chris Lattnereed48272005-09-13 00:40:14 +00006357 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6358 if (!isa<PointerType>(X->getType())) {
6359 // Not interesting. Source pointer must be a cast from pointer.
6360 } else if (HasZeroPointerIndex) {
6361 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6362 // into : GEP [10 x ubyte]* X, long 0, ...
6363 //
6364 // This occurs when the program declares an array extern like "int X[];"
6365 //
6366 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6367 const PointerType *XTy = cast<PointerType>(X->getType());
6368 if (const ArrayType *XATy =
6369 dyn_cast<ArrayType>(XTy->getElementType()))
6370 if (const ArrayType *CATy =
6371 dyn_cast<ArrayType>(CPTy->getElementType()))
6372 if (CATy->getElementType() == XATy->getElementType()) {
6373 // At this point, we know that the cast source type is a pointer
6374 // to an array of the same type as the destination pointer
6375 // array. Because the array type is never stepped over (there
6376 // is a leading zero) we can fold the cast into this GEP.
6377 GEP.setOperand(0, X);
6378 return &GEP;
6379 }
6380 } else if (GEP.getNumOperands() == 2) {
6381 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00006382 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6383 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00006384 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6385 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6386 if (isa<ArrayType>(SrcElTy) &&
6387 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6388 TD->getTypeSize(ResElTy)) {
6389 Value *V = InsertNewInstBefore(
6390 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6391 GEP.getOperand(1), GEP.getName()), GEP);
6392 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006393 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00006394
6395 // Transform things like:
6396 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6397 // (where tmp = 8*tmp2) into:
6398 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6399
6400 if (isa<ArrayType>(SrcElTy) &&
6401 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6402 uint64_t ArrayEltSize =
6403 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6404
6405 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6406 // allow either a mul, shift, or constant here.
6407 Value *NewIdx = 0;
6408 ConstantInt *Scale = 0;
6409 if (ArrayEltSize == 1) {
6410 NewIdx = GEP.getOperand(1);
6411 Scale = ConstantInt::get(NewIdx->getType(), 1);
6412 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00006413 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006414 Scale = CI;
6415 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6416 if (Inst->getOpcode() == Instruction::Shl &&
6417 isa<ConstantInt>(Inst->getOperand(1))) {
6418 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6419 if (Inst->getType()->isSigned())
6420 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6421 else
6422 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6423 NewIdx = Inst->getOperand(0);
6424 } else if (Inst->getOpcode() == Instruction::Mul &&
6425 isa<ConstantInt>(Inst->getOperand(1))) {
6426 Scale = cast<ConstantInt>(Inst->getOperand(1));
6427 NewIdx = Inst->getOperand(0);
6428 }
6429 }
6430
6431 // If the index will be to exactly the right offset with the scale taken
6432 // out, perform the transformation.
6433 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6434 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6435 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00006436 (int64_t)C->getRawValue() /
6437 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006438 else
6439 Scale = ConstantUInt::get(Scale->getType(),
6440 Scale->getRawValue() / ArrayEltSize);
6441 if (Scale->getRawValue() != 1) {
6442 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6443 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6444 NewIdx = InsertNewInstBefore(Sc, GEP);
6445 }
6446
6447 // Insert the new GEP instruction.
6448 Instruction *Idx =
6449 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6450 NewIdx, GEP.getName());
6451 Idx = InsertNewInstBefore(Idx, GEP);
6452 return new CastInst(Idx, GEP.getType());
6453 }
6454 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006455 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006456 }
6457
Chris Lattner8a2a3112001-12-14 16:52:21 +00006458 return 0;
6459}
6460
Chris Lattner0864acf2002-11-04 16:18:53 +00006461Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6462 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6463 if (AI.isArrayAllocation()) // Check C != 1
6464 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6465 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00006466 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00006467
6468 // Create and insert the replacement instruction...
6469 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00006470 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006471 else {
6472 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00006473 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006474 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006475
6476 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006477
Chris Lattner0864acf2002-11-04 16:18:53 +00006478 // Scan to the end of the allocation instructions, to skip over a block of
6479 // allocas if possible...
6480 //
6481 BasicBlock::iterator It = New;
6482 while (isa<AllocationInst>(*It)) ++It;
6483
6484 // Now that I is pointing to the first non-allocation-inst in the block,
6485 // insert our getelementptr instruction...
6486 //
Chris Lattner693787a2005-05-04 19:10:26 +00006487 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6488 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6489 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00006490
6491 // Now make everything use the getelementptr instead of the original
6492 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00006493 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00006494 } else if (isa<UndefValue>(AI.getArraySize())) {
6495 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00006496 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006497
6498 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6499 // Note that we only do this for alloca's, because malloc should allocate and
6500 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00006501 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00006502 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00006503 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6504
Chris Lattner0864acf2002-11-04 16:18:53 +00006505 return 0;
6506}
6507
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006508Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6509 Value *Op = FI.getOperand(0);
6510
6511 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6512 if (CastInst *CI = dyn_cast<CastInst>(Op))
6513 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6514 FI.setOperand(0, CI->getOperand(0));
6515 return &FI;
6516 }
6517
Chris Lattner17be6352004-10-18 02:59:09 +00006518 // free undef -> unreachable.
6519 if (isa<UndefValue>(Op)) {
6520 // Insert a new store to null because we cannot modify the CFG here.
6521 new StoreInst(ConstantBool::True,
6522 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6523 return EraseInstFromFunction(FI);
6524 }
6525
Chris Lattner6160e852004-02-28 04:57:37 +00006526 // If we have 'free null' delete the instruction. This can happen in stl code
6527 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00006528 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006529 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00006530
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006531 return 0;
6532}
6533
6534
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006535/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00006536static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6537 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00006538 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00006539
6540 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006541 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00006542 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006543
Chris Lattnera1c35382006-04-02 05:37:12 +00006544 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6545 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00006546 // If the source is an array, the code below will not succeed. Check to
6547 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6548 // constants.
6549 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6550 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6551 if (ASrcTy->getNumElements() != 0) {
6552 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6553 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6554 SrcTy = cast<PointerType>(CastOp->getType());
6555 SrcPTy = SrcTy->getElementType();
6556 }
6557
Chris Lattnera1c35382006-04-02 05:37:12 +00006558 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6559 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00006560 // Do not allow turning this into a load of an integer, which is then
6561 // casted to a pointer, this pessimizes pointer analysis a lot.
6562 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006563 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00006564 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00006565
Chris Lattnerf9527852005-01-31 04:50:46 +00006566 // Okay, we are casting from one integer or pointer type to another of
6567 // the same size. Instead of casting the pointer before the load, cast
6568 // the result of the loaded value.
6569 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6570 CI->getName(),
6571 LI.isVolatile()),LI);
6572 // Now cast the result of the load.
6573 return new CastInst(NewLoad, LI.getType());
6574 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00006575 }
6576 }
6577 return 0;
6578}
6579
Chris Lattnerc10aced2004-09-19 18:43:46 +00006580/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00006581/// from this value cannot trap. If it is not obviously safe to load from the
6582/// specified pointer, we do a quick local scan of the basic block containing
6583/// ScanFrom, to determine if the address is already accessed.
6584static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6585 // If it is an alloca or global variable, it is always safe to load from.
6586 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6587
6588 // Otherwise, be a little bit agressive by scanning the local block where we
6589 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006590 // from/to. If so, the previous load or store would have already trapped,
6591 // so there is no harm doing an extra load (also, CSE will later eliminate
6592 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00006593 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6594
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006595 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00006596 --BBI;
6597
6598 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6599 if (LI->getOperand(0) == V) return true;
6600 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6601 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00006602
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006603 }
Chris Lattner8a375202004-09-19 19:18:10 +00006604 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00006605}
6606
Chris Lattner833b8a42003-06-26 05:06:25 +00006607Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6608 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00006609
Chris Lattner37366c12005-05-01 04:24:53 +00006610 // load (cast X) --> cast (load X) iff safe
6611 if (CastInst *CI = dyn_cast<CastInst>(Op))
6612 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6613 return Res;
6614
6615 // None of the following transforms are legal for volatile loads.
6616 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00006617
Chris Lattner62f254d2005-09-12 22:00:15 +00006618 if (&LI.getParent()->front() != &LI) {
6619 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006620 // If the instruction immediately before this is a store to the same
6621 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00006622 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6623 if (SI->getOperand(1) == LI.getOperand(0))
6624 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006625 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6626 if (LIB->getOperand(0) == LI.getOperand(0))
6627 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00006628 }
Chris Lattner37366c12005-05-01 04:24:53 +00006629
6630 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6631 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6632 isa<UndefValue>(GEPI->getOperand(0))) {
6633 // Insert a new store to null instruction before the load to indicate
6634 // that this code is not reachable. We do this instead of inserting
6635 // an unreachable instruction directly because we cannot modify the
6636 // CFG.
6637 new StoreInst(UndefValue::get(LI.getType()),
6638 Constant::getNullValue(Op->getType()), &LI);
6639 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6640 }
6641
Chris Lattnere87597f2004-10-16 18:11:37 +00006642 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00006643 // load null/undef -> undef
6644 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00006645 // Insert a new store to null instruction before the load to indicate that
6646 // this code is not reachable. We do this instead of inserting an
6647 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00006648 new StoreInst(UndefValue::get(LI.getType()),
6649 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00006650 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00006651 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006652
Chris Lattnere87597f2004-10-16 18:11:37 +00006653 // Instcombine load (constant global) into the value loaded.
6654 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6655 if (GV->isConstant() && !GV->isExternal())
6656 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00006657
Chris Lattnere87597f2004-10-16 18:11:37 +00006658 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6659 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6660 if (CE->getOpcode() == Instruction::GetElementPtr) {
6661 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6662 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00006663 if (Constant *V =
6664 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00006665 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00006666 if (CE->getOperand(0)->isNullValue()) {
6667 // Insert a new store to null instruction before the load to indicate
6668 // that this code is not reachable. We do this instead of inserting
6669 // an unreachable instruction directly because we cannot modify the
6670 // CFG.
6671 new StoreInst(UndefValue::get(LI.getType()),
6672 Constant::getNullValue(Op->getType()), &LI);
6673 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6674 }
6675
Chris Lattnere87597f2004-10-16 18:11:37 +00006676 } else if (CE->getOpcode() == Instruction::Cast) {
6677 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6678 return Res;
6679 }
6680 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00006681
Chris Lattner37366c12005-05-01 04:24:53 +00006682 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006683 // Change select and PHI nodes to select values instead of addresses: this
6684 // helps alias analysis out a lot, allows many others simplifications, and
6685 // exposes redundancy in the code.
6686 //
6687 // Note that we cannot do the transformation unless we know that the
6688 // introduced loads cannot trap! Something like this is valid as long as
6689 // the condition is always false: load (select bool %C, int* null, int* %G),
6690 // but it would not be valid if we transformed it to load from null
6691 // unconditionally.
6692 //
6693 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6694 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00006695 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6696 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006697 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006698 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006699 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006700 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006701 return new SelectInst(SI->getCondition(), V1, V2);
6702 }
6703
Chris Lattner684fe212004-09-23 15:46:00 +00006704 // load (select (cond, null, P)) -> load P
6705 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6706 if (C->isNullValue()) {
6707 LI.setOperand(0, SI->getOperand(2));
6708 return &LI;
6709 }
6710
6711 // load (select (cond, P, null)) -> load P
6712 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6713 if (C->isNullValue()) {
6714 LI.setOperand(0, SI->getOperand(1));
6715 return &LI;
6716 }
6717
Chris Lattnerc10aced2004-09-19 18:43:46 +00006718 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6719 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006720 bool Safe = PN->getParent() == LI.getParent();
6721
6722 // Scan all of the instructions between the PHI and the load to make
6723 // sure there are no instructions that might possibly alter the value
6724 // loaded from the PHI.
6725 if (Safe) {
6726 BasicBlock::iterator I = &LI;
6727 for (--I; !isa<PHINode>(I); --I)
6728 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6729 Safe = false;
6730 break;
6731 }
6732 }
6733
6734 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00006735 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006736 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00006737 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006738
Chris Lattnerc10aced2004-09-19 18:43:46 +00006739 if (Safe) {
6740 // Create the PHI.
6741 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6742 InsertNewInstBefore(NewPN, *PN);
6743 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6744
6745 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6746 BasicBlock *BB = PN->getIncomingBlock(i);
6747 Value *&TheLoad = LoadMap[BB];
6748 if (TheLoad == 0) {
6749 Value *InVal = PN->getIncomingValue(i);
6750 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6751 InVal->getName()+".val"),
6752 *BB->getTerminator());
6753 }
6754 NewPN->addIncoming(TheLoad, BB);
6755 }
6756 return ReplaceInstUsesWith(LI, NewPN);
6757 }
6758 }
6759 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006760 return 0;
6761}
6762
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006763/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6764/// when possible.
6765static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6766 User *CI = cast<User>(SI.getOperand(1));
6767 Value *CastOp = CI->getOperand(0);
6768
6769 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6770 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6771 const Type *SrcPTy = SrcTy->getElementType();
6772
6773 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6774 // If the source is an array, the code below will not succeed. Check to
6775 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6776 // constants.
6777 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6778 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6779 if (ASrcTy->getNumElements() != 0) {
6780 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6781 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6782 SrcTy = cast<PointerType>(CastOp->getType());
6783 SrcPTy = SrcTy->getElementType();
6784 }
6785
6786 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006787 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006788 IC.getTargetData().getTypeSize(DestPTy)) {
6789
6790 // Okay, we are casting from one integer or pointer type to another of
6791 // the same size. Instead of casting the pointer before the store, cast
6792 // the value to be stored.
6793 Value *NewCast;
6794 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6795 NewCast = ConstantExpr::getCast(C, SrcPTy);
6796 else
6797 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6798 SrcPTy,
6799 SI.getOperand(0)->getName()+".c"), SI);
6800
6801 return new StoreInst(NewCast, CastOp);
6802 }
6803 }
6804 }
6805 return 0;
6806}
6807
Chris Lattner2f503e62005-01-31 05:36:43 +00006808Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6809 Value *Val = SI.getOperand(0);
6810 Value *Ptr = SI.getOperand(1);
6811
6812 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00006813 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006814 ++NumCombined;
6815 return 0;
6816 }
6817
Chris Lattner9ca96412006-02-08 03:25:32 +00006818 // Do really simple DSE, to catch cases where there are several consequtive
6819 // stores to the same location, separated by a few arithmetic operations. This
6820 // situation often occurs with bitfield accesses.
6821 BasicBlock::iterator BBI = &SI;
6822 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6823 --ScanInsts) {
6824 --BBI;
6825
6826 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6827 // Prev store isn't volatile, and stores to the same location?
6828 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6829 ++NumDeadStore;
6830 ++BBI;
6831 EraseInstFromFunction(*PrevSI);
6832 continue;
6833 }
6834 break;
6835 }
6836
Chris Lattnerb4db97f2006-05-26 19:19:20 +00006837 // If this is a load, we have to stop. However, if the loaded value is from
6838 // the pointer we're loading and is producing the pointer we're storing,
6839 // then *this* store is dead (X = load P; store X -> P).
6840 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6841 if (LI == Val && LI->getOperand(0) == Ptr) {
6842 EraseInstFromFunction(SI);
6843 ++NumCombined;
6844 return 0;
6845 }
6846 // Otherwise, this is a load from some other location. Stores before it
6847 // may not be dead.
6848 break;
6849 }
6850
Chris Lattner9ca96412006-02-08 03:25:32 +00006851 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00006852 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00006853 break;
6854 }
6855
6856
6857 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00006858
6859 // store X, null -> turns into 'unreachable' in SimplifyCFG
6860 if (isa<ConstantPointerNull>(Ptr)) {
6861 if (!isa<UndefValue>(Val)) {
6862 SI.setOperand(0, UndefValue::get(Val->getType()));
6863 if (Instruction *U = dyn_cast<Instruction>(Val))
6864 WorkList.push_back(U); // Dropped a use.
6865 ++NumCombined;
6866 }
6867 return 0; // Do not modify these!
6868 }
6869
6870 // store undef, Ptr -> noop
6871 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00006872 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006873 ++NumCombined;
6874 return 0;
6875 }
6876
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006877 // If the pointer destination is a cast, see if we can fold the cast into the
6878 // source instead.
6879 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6880 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6881 return Res;
6882 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6883 if (CE->getOpcode() == Instruction::Cast)
6884 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6885 return Res;
6886
Chris Lattner408902b2005-09-12 23:23:25 +00006887
6888 // If this store is the last instruction in the basic block, and if the block
6889 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00006890 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00006891 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6892 if (BI->isUnconditional()) {
6893 // Check to see if the successor block has exactly two incoming edges. If
6894 // so, see if the other predecessor contains a store to the same location.
6895 // if so, insert a PHI node (if needed) and move the stores down.
6896 BasicBlock *Dest = BI->getSuccessor(0);
6897
6898 pred_iterator PI = pred_begin(Dest);
6899 BasicBlock *Other = 0;
6900 if (*PI != BI->getParent())
6901 Other = *PI;
6902 ++PI;
6903 if (PI != pred_end(Dest)) {
6904 if (*PI != BI->getParent())
6905 if (Other)
6906 Other = 0;
6907 else
6908 Other = *PI;
6909 if (++PI != pred_end(Dest))
6910 Other = 0;
6911 }
6912 if (Other) { // If only one other pred...
6913 BBI = Other->getTerminator();
6914 // Make sure this other block ends in an unconditional branch and that
6915 // there is an instruction before the branch.
6916 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6917 BBI != Other->begin()) {
6918 --BBI;
6919 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6920
6921 // If this instruction is a store to the same location.
6922 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6923 // Okay, we know we can perform this transformation. Insert a PHI
6924 // node now if we need it.
6925 Value *MergedVal = OtherStore->getOperand(0);
6926 if (MergedVal != SI.getOperand(0)) {
6927 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6928 PN->reserveOperandSpace(2);
6929 PN->addIncoming(SI.getOperand(0), SI.getParent());
6930 PN->addIncoming(OtherStore->getOperand(0), Other);
6931 MergedVal = InsertNewInstBefore(PN, Dest->front());
6932 }
6933
6934 // Advance to a place where it is safe to insert the new store and
6935 // insert it.
6936 BBI = Dest->begin();
6937 while (isa<PHINode>(BBI)) ++BBI;
6938 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6939 OtherStore->isVolatile()), *BBI);
6940
6941 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00006942 EraseInstFromFunction(SI);
6943 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00006944 ++NumCombined;
6945 return 0;
6946 }
6947 }
6948 }
6949 }
6950
Chris Lattner2f503e62005-01-31 05:36:43 +00006951 return 0;
6952}
6953
6954
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006955Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6956 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00006957 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006958 BasicBlock *TrueDest;
6959 BasicBlock *FalseDest;
6960 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6961 !isa<Constant>(X)) {
6962 // Swap Destinations and condition...
6963 BI.setCondition(X);
6964 BI.setSuccessor(0, FalseDest);
6965 BI.setSuccessor(1, TrueDest);
6966 return &BI;
6967 }
6968
6969 // Cannonicalize setne -> seteq
6970 Instruction::BinaryOps Op; Value *Y;
6971 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6972 TrueDest, FalseDest)))
6973 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6974 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6975 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6976 std::string Name = I->getName(); I->setName("");
6977 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6978 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00006979 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006980 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00006981 BI.setSuccessor(0, FalseDest);
6982 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006983 removeFromWorkList(I);
6984 I->getParent()->getInstList().erase(I);
6985 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00006986 return &BI;
6987 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006988
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006989 return 0;
6990}
Chris Lattner0864acf2002-11-04 16:18:53 +00006991
Chris Lattner46238a62004-07-03 00:26:11 +00006992Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6993 Value *Cond = SI.getCondition();
6994 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6995 if (I->getOpcode() == Instruction::Add)
6996 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6997 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6998 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00006999 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00007000 AddRHS));
7001 SI.setOperand(0, I->getOperand(0));
7002 WorkList.push_back(I);
7003 return &SI;
7004 }
7005 }
7006 return 0;
7007}
7008
Chris Lattner220b0cf2006-03-05 00:22:33 +00007009/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7010/// is to leave as a vector operation.
7011static bool CheapToScalarize(Value *V, bool isConstant) {
7012 if (isa<ConstantAggregateZero>(V))
7013 return true;
7014 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7015 if (isConstant) return true;
7016 // If all elts are the same, we can extract.
7017 Constant *Op0 = C->getOperand(0);
7018 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7019 if (C->getOperand(i) != Op0)
7020 return false;
7021 return true;
7022 }
7023 Instruction *I = dyn_cast<Instruction>(V);
7024 if (!I) return false;
7025
7026 // Insert element gets simplified to the inserted element or is deleted if
7027 // this is constant idx extract element and its a constant idx insertelt.
7028 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7029 isa<ConstantInt>(I->getOperand(2)))
7030 return true;
7031 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7032 return true;
7033 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7034 if (BO->hasOneUse() &&
7035 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7036 CheapToScalarize(BO->getOperand(1), isConstant)))
7037 return true;
7038
7039 return false;
7040}
7041
Chris Lattner863bcff2006-05-25 23:48:38 +00007042/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7043/// elements into values that are larger than the #elts in the input.
7044static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7045 unsigned NElts = SVI->getType()->getNumElements();
7046 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7047 return std::vector<unsigned>(NElts, 0);
7048 if (isa<UndefValue>(SVI->getOperand(2)))
7049 return std::vector<unsigned>(NElts, 2*NElts);
7050
7051 std::vector<unsigned> Result;
7052 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7053 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7054 if (isa<UndefValue>(CP->getOperand(i)))
7055 Result.push_back(NElts*2); // undef -> 8
7056 else
7057 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7058 return Result;
7059}
7060
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007061/// FindScalarElement - Given a vector and an element number, see if the scalar
7062/// value is already around as a register, for example if it were inserted then
7063/// extracted from the vector.
7064static Value *FindScalarElement(Value *V, unsigned EltNo) {
7065 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7066 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00007067 unsigned Width = PTy->getNumElements();
7068 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007069 return UndefValue::get(PTy->getElementType());
7070
7071 if (isa<UndefValue>(V))
7072 return UndefValue::get(PTy->getElementType());
7073 else if (isa<ConstantAggregateZero>(V))
7074 return Constant::getNullValue(PTy->getElementType());
7075 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7076 return CP->getOperand(EltNo);
7077 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7078 // If this is an insert to a variable element, we don't know what it is.
7079 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7080 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7081
7082 // If this is an insert to the element we are looking for, return the
7083 // inserted value.
7084 if (EltNo == IIElt) return III->getOperand(1);
7085
7086 // Otherwise, the insertelement doesn't modify the value, recurse on its
7087 // vector input.
7088 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00007089 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00007090 unsigned InEl = getShuffleMask(SVI)[EltNo];
7091 if (InEl < Width)
7092 return FindScalarElement(SVI->getOperand(0), InEl);
7093 else if (InEl < Width*2)
7094 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7095 else
7096 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007097 }
7098
7099 // Otherwise, we don't know.
7100 return 0;
7101}
7102
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007103Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007104
Chris Lattner1f13c882006-03-31 18:25:14 +00007105 // If packed val is undef, replace extract with scalar undef.
7106 if (isa<UndefValue>(EI.getOperand(0)))
7107 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7108
7109 // If packed val is constant 0, replace extract with scalar 0.
7110 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7111 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7112
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007113 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7114 // If packed val is constant with uniform operands, replace EI
7115 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00007116 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007117 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00007118 if (C->getOperand(i) != op0) {
7119 op0 = 0;
7120 break;
7121 }
7122 if (op0)
7123 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007124 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00007125
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007126 // If extracting a specified index from the vector, see if we can recursively
7127 // find a previously computed scalar that was inserted into the vector.
Chris Lattner389a6f52006-04-10 23:06:36 +00007128 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007129 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7130 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00007131 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007132
Chris Lattner73fa49d2006-05-25 22:53:38 +00007133 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007134 if (I->hasOneUse()) {
7135 // Push extractelement into predecessor operation if legal and
7136 // profitable to do so
7137 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00007138 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7139 if (CheapToScalarize(BO, isConstantElt)) {
7140 ExtractElementInst *newEI0 =
7141 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7142 EI.getName()+".lhs");
7143 ExtractElementInst *newEI1 =
7144 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7145 EI.getName()+".rhs");
7146 InsertNewInstBefore(newEI0, EI);
7147 InsertNewInstBefore(newEI1, EI);
7148 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7149 }
7150 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007151 Value *Ptr = InsertCastBefore(I->getOperand(0),
7152 PointerType::get(EI.getType()), EI);
7153 GetElementPtrInst *GEP =
7154 new GetElementPtrInst(Ptr, EI.getOperand(1),
7155 I->getName() + ".gep");
7156 InsertNewInstBefore(GEP, EI);
7157 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00007158 }
7159 }
7160 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7161 // Extracting the inserted element?
7162 if (IE->getOperand(2) == EI.getOperand(1))
7163 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7164 // If the inserted and extracted elements are constants, they must not
7165 // be the same value, extract from the pre-inserted value instead.
7166 if (isa<Constant>(IE->getOperand(2)) &&
7167 isa<Constant>(EI.getOperand(1))) {
7168 AddUsesToWorkList(EI);
7169 EI.setOperand(0, IE->getOperand(0));
7170 return &EI;
7171 }
7172 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7173 // If this is extracting an element from a shufflevector, figure out where
7174 // it came from and extract from the appropriate input element instead.
7175 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner863bcff2006-05-25 23:48:38 +00007176 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7177 Value *Src;
7178 if (SrcIdx < SVI->getType()->getNumElements())
7179 Src = SVI->getOperand(0);
7180 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7181 SrcIdx -= SVI->getType()->getNumElements();
7182 Src = SVI->getOperand(1);
7183 } else {
7184 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00007185 }
Chris Lattner863bcff2006-05-25 23:48:38 +00007186 return new ExtractElementInst(Src,
7187 ConstantUInt::get(Type::UIntTy, SrcIdx));
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007188 }
7189 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00007190 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007191 return 0;
7192}
7193
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007194/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7195/// elements from either LHS or RHS, return the shuffle mask and true.
7196/// Otherwise, return false.
7197static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7198 std::vector<Constant*> &Mask) {
7199 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7200 "Invalid CollectSingleShuffleElements");
7201 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7202
7203 if (isa<UndefValue>(V)) {
7204 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7205 return true;
7206 } else if (V == LHS) {
7207 for (unsigned i = 0; i != NumElts; ++i)
7208 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7209 return true;
7210 } else if (V == RHS) {
7211 for (unsigned i = 0; i != NumElts; ++i)
7212 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7213 return true;
7214 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7215 // If this is an insert of an extract from some other vector, include it.
7216 Value *VecOp = IEI->getOperand(0);
7217 Value *ScalarOp = IEI->getOperand(1);
7218 Value *IdxOp = IEI->getOperand(2);
7219
Chris Lattnerd929f062006-04-27 21:14:21 +00007220 if (!isa<ConstantInt>(IdxOp))
7221 return false;
7222 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7223
7224 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7225 // Okay, we can handle this if the vector we are insertinting into is
7226 // transitively ok.
7227 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7228 // If so, update the mask to reflect the inserted undef.
7229 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7230 return true;
7231 }
7232 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7233 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007234 EI->getOperand(0)->getType() == V->getType()) {
7235 unsigned ExtractedIdx =
7236 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007237
7238 // This must be extracting from either LHS or RHS.
7239 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7240 // Okay, we can handle this if the vector we are insertinting into is
7241 // transitively ok.
7242 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7243 // If so, update the mask to reflect the inserted value.
7244 if (EI->getOperand(0) == LHS) {
7245 Mask[InsertedIdx & (NumElts-1)] =
7246 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7247 } else {
7248 assert(EI->getOperand(0) == RHS);
7249 Mask[InsertedIdx & (NumElts-1)] =
7250 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7251
7252 }
7253 return true;
7254 }
7255 }
7256 }
7257 }
7258 }
7259 // TODO: Handle shufflevector here!
7260
7261 return false;
7262}
7263
7264/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7265/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7266/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00007267static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007268 Value *&RHS) {
7269 assert(isa<PackedType>(V->getType()) &&
7270 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00007271 "Invalid shuffle!");
7272 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7273
7274 if (isa<UndefValue>(V)) {
7275 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7276 return V;
7277 } else if (isa<ConstantAggregateZero>(V)) {
7278 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7279 return V;
7280 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7281 // If this is an insert of an extract from some other vector, include it.
7282 Value *VecOp = IEI->getOperand(0);
7283 Value *ScalarOp = IEI->getOperand(1);
7284 Value *IdxOp = IEI->getOperand(2);
7285
7286 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7287 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7288 EI->getOperand(0)->getType() == V->getType()) {
7289 unsigned ExtractedIdx =
7290 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7291 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7292
7293 // Either the extracted from or inserted into vector must be RHSVec,
7294 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007295 if (EI->getOperand(0) == RHS || RHS == 0) {
7296 RHS = EI->getOperand(0);
7297 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007298 Mask[InsertedIdx & (NumElts-1)] =
7299 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7300 return V;
7301 }
7302
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007303 if (VecOp == RHS) {
7304 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007305 // Everything but the extracted element is replaced with the RHS.
7306 for (unsigned i = 0; i != NumElts; ++i) {
7307 if (i != InsertedIdx)
7308 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7309 }
7310 return V;
7311 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007312
7313 // If this insertelement is a chain that comes from exactly these two
7314 // vectors, return the vector and the effective shuffle.
7315 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7316 return EI->getOperand(0);
7317
Chris Lattnerefb47352006-04-15 01:39:45 +00007318 }
7319 }
7320 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007321 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00007322
7323 // Otherwise, can't do anything fancy. Return an identity vector.
7324 for (unsigned i = 0; i != NumElts; ++i)
7325 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7326 return V;
7327}
7328
7329Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7330 Value *VecOp = IE.getOperand(0);
7331 Value *ScalarOp = IE.getOperand(1);
7332 Value *IdxOp = IE.getOperand(2);
7333
7334 // If the inserted element was extracted from some other vector, and if the
7335 // indexes are constant, try to turn this into a shufflevector operation.
7336 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7337 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7338 EI->getOperand(0)->getType() == IE.getType()) {
7339 unsigned NumVectorElts = IE.getType()->getNumElements();
7340 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7341 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7342
7343 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7344 return ReplaceInstUsesWith(IE, VecOp);
7345
7346 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7347 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7348
7349 // If we are extracting a value from a vector, then inserting it right
7350 // back into the same place, just use the input vector.
7351 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7352 return ReplaceInstUsesWith(IE, VecOp);
7353
7354 // We could theoretically do this for ANY input. However, doing so could
7355 // turn chains of insertelement instructions into a chain of shufflevector
7356 // instructions, and right now we do not merge shufflevectors. As such,
7357 // only do this in a situation where it is clear that there is benefit.
7358 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7359 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7360 // the values of VecOp, except then one read from EIOp0.
7361 // Build a new shuffle mask.
7362 std::vector<Constant*> Mask;
7363 if (isa<UndefValue>(VecOp))
7364 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7365 else {
7366 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7367 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7368 NumVectorElts));
7369 }
7370 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7371 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7372 ConstantPacked::get(Mask));
7373 }
7374
7375 // If this insertelement isn't used by some other insertelement, turn it
7376 // (and any insertelements it points to), into one big shuffle.
7377 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7378 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007379 Value *RHS = 0;
7380 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7381 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7382 // We now have a shuffle of LHS, RHS, Mask.
7383 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00007384 }
7385 }
7386 }
7387
7388 return 0;
7389}
7390
7391
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007392Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7393 Value *LHS = SVI.getOperand(0);
7394 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00007395 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007396
7397 bool MadeChange = false;
7398
Chris Lattner863bcff2006-05-25 23:48:38 +00007399 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007400 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7401
Chris Lattnerefb47352006-04-15 01:39:45 +00007402 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7403 // the undef, change them to undefs.
7404
Chris Lattner863bcff2006-05-25 23:48:38 +00007405 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7406 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7407 if (LHS == RHS || isa<UndefValue>(LHS)) {
7408 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007409 // shuffle(undef,undef,mask) -> undef.
7410 return ReplaceInstUsesWith(SVI, LHS);
7411 }
7412
Chris Lattner863bcff2006-05-25 23:48:38 +00007413 // Remap any references to RHS to use LHS.
7414 std::vector<Constant*> Elts;
7415 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00007416 if (Mask[i] >= 2*e)
Chris Lattner863bcff2006-05-25 23:48:38 +00007417 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner7b2e27922006-05-26 00:29:06 +00007418 else {
7419 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7420 (Mask[i] < e && isa<UndefValue>(LHS)))
7421 Mask[i] = 2*e; // Turn into undef.
7422 else
7423 Mask[i] &= (e-1); // Force to LHS.
7424 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7425 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007426 }
Chris Lattner863bcff2006-05-25 23:48:38 +00007427 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007428 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner863bcff2006-05-25 23:48:38 +00007429 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00007430 LHS = SVI.getOperand(0);
7431 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007432 MadeChange = true;
7433 }
7434
Chris Lattner7b2e27922006-05-26 00:29:06 +00007435 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00007436 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00007437
Chris Lattner863bcff2006-05-25 23:48:38 +00007438 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7439 if (Mask[i] >= e*2) continue; // Ignore undef values.
7440 // Is this an identity shuffle of the LHS value?
7441 isLHSID &= (Mask[i] == i);
7442
7443 // Is this an identity shuffle of the RHS value?
7444 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00007445 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007446
Chris Lattner863bcff2006-05-25 23:48:38 +00007447 // Eliminate identity shuffles.
7448 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7449 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007450
Chris Lattner7b2e27922006-05-26 00:29:06 +00007451 // If the LHS is a shufflevector itself, see if we can combine it with this
7452 // one without producing an unusual shuffle. Here we are really conservative:
7453 // we are absolutely afraid of producing a shuffle mask not in the input
7454 // program, because the code gen may not be smart enough to turn a merged
7455 // shuffle into two specific shuffles: it may produce worse code. As such,
7456 // we only merge two shuffles if the result is one of the two input shuffle
7457 // masks. In this case, merging the shuffles just removes one instruction,
7458 // which we know is safe. This is good for things like turning:
7459 // (splat(splat)) -> splat.
7460 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7461 if (isa<UndefValue>(RHS)) {
7462 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7463
7464 std::vector<unsigned> NewMask;
7465 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7466 if (Mask[i] >= 2*e)
7467 NewMask.push_back(2*e);
7468 else
7469 NewMask.push_back(LHSMask[Mask[i]]);
7470
7471 // If the result mask is equal to the src shuffle or this shuffle mask, do
7472 // the replacement.
7473 if (NewMask == LHSMask || NewMask == Mask) {
7474 std::vector<Constant*> Elts;
7475 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7476 if (NewMask[i] >= e*2) {
7477 Elts.push_back(UndefValue::get(Type::UIntTy));
7478 } else {
7479 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7480 }
7481 }
7482 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7483 LHSSVI->getOperand(1),
7484 ConstantPacked::get(Elts));
7485 }
7486 }
7487 }
7488
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007489 return MadeChange ? &SVI : 0;
7490}
7491
7492
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007493
Chris Lattner62b14df2002-09-02 04:59:56 +00007494void InstCombiner::removeFromWorkList(Instruction *I) {
7495 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7496 WorkList.end());
7497}
7498
Chris Lattnerea1c4542004-12-08 23:43:58 +00007499
7500/// TryToSinkInstruction - Try to move the specified instruction from its
7501/// current block into the beginning of DestBlock, which can only happen if it's
7502/// safe to move the instruction past all of the instructions between it and the
7503/// end of its block.
7504static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7505 assert(I->hasOneUse() && "Invariants didn't hold!");
7506
Chris Lattner108e9022005-10-27 17:13:11 +00007507 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7508 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00007509
Chris Lattnerea1c4542004-12-08 23:43:58 +00007510 // Do not sink alloca instructions out of the entry block.
7511 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7512 return false;
7513
Chris Lattner96a52a62004-12-09 07:14:34 +00007514 // We can only sink load instructions if there is nothing between the load and
7515 // the end of block that could change the value.
7516 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00007517 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7518 Scan != E; ++Scan)
7519 if (Scan->mayWriteToMemory())
7520 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00007521 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00007522
7523 BasicBlock::iterator InsertPos = DestBlock->begin();
7524 while (isa<PHINode>(InsertPos)) ++InsertPos;
7525
Chris Lattner4bc5f802005-08-08 19:11:57 +00007526 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00007527 ++NumSunkInst;
7528 return true;
7529}
7530
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007531/// OptimizeConstantExpr - Given a constant expression and target data layout
7532/// information, symbolically evaluation the constant expr to something simpler
7533/// if possible.
7534static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7535 if (!TD) return CE;
7536
7537 Constant *Ptr = CE->getOperand(0);
7538 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7539 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7540 // If this is a constant expr gep that is effectively computing an
7541 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7542 bool isFoldableGEP = true;
7543 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7544 if (!isa<ConstantInt>(CE->getOperand(i)))
7545 isFoldableGEP = false;
7546 if (isFoldableGEP) {
7547 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7548 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7549 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7550 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7551 return ConstantExpr::getCast(C, CE->getType());
7552 }
7553 }
7554
7555 return CE;
7556}
7557
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007558
7559/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7560/// all reachable code to the worklist.
7561///
7562/// This has a couple of tricks to make the code faster and more powerful. In
7563/// particular, we constant fold and DCE instructions as we go, to avoid adding
7564/// them to the worklist (this significantly speeds up instcombine on code where
7565/// many instructions are dead or constant). Additionally, if we find a branch
7566/// whose condition is a known constant, we only visit the reachable successors.
7567///
7568static void AddReachableCodeToWorklist(BasicBlock *BB,
7569 std::set<BasicBlock*> &Visited,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007570 std::vector<Instruction*> &WorkList,
7571 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007572 // We have now visited this block! If we've already been here, bail out.
7573 if (!Visited.insert(BB).second) return;
7574
7575 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7576 Instruction *Inst = BBI++;
7577
7578 // DCE instruction if trivially dead.
7579 if (isInstructionTriviallyDead(Inst)) {
7580 ++NumDeadInst;
7581 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7582 Inst->eraseFromParent();
7583 continue;
7584 }
7585
7586 // ConstantProp instruction if trivially constant.
7587 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007588 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7589 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007590 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7591 Inst->replaceAllUsesWith(C);
7592 ++NumConstProp;
7593 Inst->eraseFromParent();
7594 continue;
7595 }
7596
7597 WorkList.push_back(Inst);
7598 }
7599
7600 // Recursively visit successors. If this is a branch or switch on a constant,
7601 // only visit the reachable successor.
7602 TerminatorInst *TI = BB->getTerminator();
7603 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7604 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7605 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007606 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7607 TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007608 return;
7609 }
7610 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7611 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7612 // See if this is an explicit destination.
7613 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7614 if (SI->getCaseValue(i) == Cond) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007615 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007616 return;
7617 }
7618
7619 // Otherwise it is the default destination.
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007620 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007621 return;
7622 }
7623 }
7624
7625 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007626 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007627}
7628
Chris Lattner7e708292002-06-25 16:13:24 +00007629bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007630 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00007631 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00007632
Chris Lattnerb3d59702005-07-07 20:40:38 +00007633 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007634 // Do a depth-first traversal of the function, populate the worklist with
7635 // the reachable instructions. Ignore blocks that are not reachable. Keep
7636 // track of which blocks we visit.
Chris Lattnerb3d59702005-07-07 20:40:38 +00007637 std::set<BasicBlock*> Visited;
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007638 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00007639
Chris Lattnerb3d59702005-07-07 20:40:38 +00007640 // Do a quick scan over the function. If we find any blocks that are
7641 // unreachable, remove any instructions inside of them. This prevents
7642 // the instcombine code from having to deal with some bad special cases.
7643 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7644 if (!Visited.count(BB)) {
7645 Instruction *Term = BB->getTerminator();
7646 while (Term != BB->begin()) { // Remove instrs bottom-up
7647 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00007648
Chris Lattnerb3d59702005-07-07 20:40:38 +00007649 DEBUG(std::cerr << "IC: DCE: " << *I);
7650 ++NumDeadInst;
7651
7652 if (!I->use_empty())
7653 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7654 I->eraseFromParent();
7655 }
7656 }
7657 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007658
7659 while (!WorkList.empty()) {
7660 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7661 WorkList.pop_back();
7662
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007663 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00007664 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007665 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00007666 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007667 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00007668 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00007669
Chris Lattnerad5fec12005-01-28 19:32:01 +00007670 DEBUG(std::cerr << "IC: DCE: " << *I);
7671
7672 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00007673 removeFromWorkList(I);
7674 continue;
7675 }
Chris Lattner62b14df2002-09-02 04:59:56 +00007676
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007677 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner62b14df2002-09-02 04:59:56 +00007678 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007679 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7680 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerad5fec12005-01-28 19:32:01 +00007681 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7682
Chris Lattner8c8c66a2006-05-11 17:11:52 +00007683 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007684 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00007685 ReplaceInstUsesWith(*I, C);
7686
Chris Lattner62b14df2002-09-02 04:59:56 +00007687 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007688 I->eraseFromParent();
Chris Lattner60610002003-10-07 15:17:02 +00007689 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007690 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00007691 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00007692
Chris Lattnerea1c4542004-12-08 23:43:58 +00007693 // See if we can trivially sink this instruction to a successor basic block.
7694 if (I->hasOneUse()) {
7695 BasicBlock *BB = I->getParent();
7696 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7697 if (UserParent != BB) {
7698 bool UserIsSuccessor = false;
7699 // See if the user is one of our successors.
7700 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7701 if (*SI == UserParent) {
7702 UserIsSuccessor = true;
7703 break;
7704 }
7705
7706 // If the user is one of our immediate successors, and if that successor
7707 // only has us as a predecessors (we'd have to split the critical edge
7708 // otherwise), we can keep going.
7709 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7710 next(pred_begin(UserParent)) == pred_end(UserParent))
7711 // Okay, the CFG is simple enough, try to sink this instruction.
7712 Changed |= TryToSinkInstruction(I, UserParent);
7713 }
7714 }
7715
Chris Lattner8a2a3112001-12-14 16:52:21 +00007716 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00007717 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00007718 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007719 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007720 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007721 DEBUG(std::cerr << "IC: Old = " << *I
7722 << " New = " << *Result);
7723
Chris Lattnerf523d062004-06-09 05:08:07 +00007724 // Everything uses the new instruction now.
7725 I->replaceAllUsesWith(Result);
7726
7727 // Push the new instruction and any users onto the worklist.
7728 WorkList.push_back(Result);
7729 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007730
7731 // Move the name to the new instruction first...
7732 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00007733 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007734
7735 // Insert the new instruction into the basic block...
7736 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00007737 BasicBlock::iterator InsertPos = I;
7738
7739 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7740 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7741 ++InsertPos;
7742
7743 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007744
Chris Lattner00d51312004-05-01 23:27:23 +00007745 // Make sure that we reprocess all operands now that we reduced their
7746 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00007747 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7748 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7749 WorkList.push_back(OpI);
7750
Chris Lattnerf523d062004-06-09 05:08:07 +00007751 // Instructions can end up on the worklist more than once. Make sure
7752 // we do not process an instruction that has been deleted.
7753 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007754
7755 // Erase the old instruction.
7756 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00007757 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007758 DEBUG(std::cerr << "IC: MOD = " << *I);
7759
Chris Lattner90ac28c2002-08-02 19:29:35 +00007760 // If the instruction was modified, it's possible that it is now dead.
7761 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00007762 if (isInstructionTriviallyDead(I)) {
7763 // Make sure we process all operands now that we are reducing their
7764 // use counts.
7765 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7766 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7767 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007768
Chris Lattner00d51312004-05-01 23:27:23 +00007769 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007770 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00007771 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00007772 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00007773 } else {
7774 WorkList.push_back(Result);
7775 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00007776 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007777 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007778 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007779 }
7780 }
7781
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007782 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007783}
7784
Brian Gaeke96d4bf72004-07-27 17:43:21 +00007785FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007786 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007787}
Brian Gaeked0fde302003-11-11 22:41:34 +00007788