blob: bb15e3504cc2deebc90d85340e0a0e20d50b2476 [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp 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 Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000198
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000202 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000205 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000217 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000220 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000225 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000226 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000227 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000228 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000229 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000230 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000231 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000234
235 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000236 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000237
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000239 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000244 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000245
Chris Lattner28977af2004-04-05 01:30:19 +0000246 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000247 // InsertNewInstBefore - insert an instruction New before instruction Old
248 // in the program. Add the new instruction to the worklist.
249 //
Chris Lattner955f3312004-09-28 21:48:02 +0000250 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000251 assert(New && New->getParent() == 0 &&
252 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000253 BasicBlock *BB = Old.getParent();
254 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000255 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000256 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000257 }
258
Chris Lattner0c967662004-09-24 15:21:34 +0000259 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260 /// This also adds the cast to the worklist. Finally, this returns the
261 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000262 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
263 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000264 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000265
Chris Lattnere2ed0572006-04-06 19:19:17 +0000266 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000267 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000268
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000269 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000270 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000271 return C;
272 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000273
274 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278
Chris Lattner8b170942002-08-09 23:47:40 +0000279 // ReplaceInstUsesWith - This method is to be used when an instruction is
280 // found to be dead, replacable with another preexisting expression. Here
281 // we add all uses of I to the worklist, replace all uses of I with the new
282 // value, then return I, so that the inst combiner will know that I was
283 // modified.
284 //
285 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000286 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000287 if (&I != V) {
288 I.replaceAllUsesWith(V);
289 return &I;
290 } else {
291 // If we are replacing the instruction with itself, this must be in a
292 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000293 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000294 return &I;
295 }
Chris Lattner8b170942002-08-09 23:47:40 +0000296 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000297
Chris Lattner6dce1a72006-02-07 06:56:34 +0000298 // UpdateValueUsesWith - This method is to be used when an value is
299 // found to be replacable with another preexisting expression or was
300 // updated. Here we add all uses of I to the worklist, replace all uses of
301 // I with the new value (unless the instruction was just updated), then
302 // return true, so that the inst combiner will know that I was modified.
303 //
304 bool UpdateValueUsesWith(Value *Old, Value *New) {
305 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
306 if (Old != New)
307 Old->replaceAllUsesWith(New);
308 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000309 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000310 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000311 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000312 return true;
313 }
314
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
318 // this function.
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000322 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000323 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000324 return 0; // Don't do anything with FI
325 }
326
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000327 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329 /// InsertBefore instruction. This is specialized a bit to avoid inserting
330 /// casts that are known to not do anything...
331 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000332 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000334 Instruction *InsertBefore);
335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000338 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000339
Reid Spencere4d87aa2006-12-23 06:05:41 +0000340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
343
Reid Spencer2ec619a2007-03-23 21:24:59 +0000344 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000346 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
348 unsigned Depth = 0);
349
Chris Lattner867b99f2006-10-05 06:55:50 +0000350 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351 uint64_t &UndefElts, unsigned Depth = 0);
352
Chris Lattner4e998b22004-09-29 05:07:12 +0000353 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354 // PHI node as operand #0, see if we can fold the instruction into the PHI
355 // (which is only possible if all operands to the PHI are constants).
356 Instruction *FoldOpIntoPhi(Instruction &I);
357
Chris Lattnerbac32862004-11-14 19:13:23 +0000358 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359 // operator and they all are only used by the PHI, PHI together their
360 // inputs, and do the operation once, to the result of the PHI.
361 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000362 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
363
364
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000365 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000367
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000368 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000369 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000370 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000371 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000372 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000373 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000374 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000375 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000376 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000377
Chris Lattnerafe91a52006-06-15 19:07:26 +0000378
Reid Spencerc55b2432006-12-13 18:21:21 +0000379 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000380
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000381 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Dan Gohman45b4e482008-05-19 22:14:15 +0000382 APInt& KnownOne, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000383 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
Dan Gohman45b4e482008-05-19 22:14:15 +0000384 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000385 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
386 unsigned CastOpc,
387 int &NumCastsRemoved);
388 unsigned GetOrEnforceKnownAlignment(Value *V,
389 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390 };
391}
392
Dan Gohman844731a2008-05-13 00:00:25 +0000393char InstCombiner::ID = 0;
394static RegisterPass<InstCombiner>
395X("instcombine", "Combine redundant instructions");
396
Chris Lattner4f98c562003-03-10 21:43:22 +0000397// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000398// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000399static unsigned getComplexity(Value *V) {
400 if (isa<Instruction>(V)) {
401 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000402 return 3;
403 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000404 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000405 if (isa<Argument>(V)) return 3;
406 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000407}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000408
Chris Lattnerc8802d22003-03-11 00:12:48 +0000409// isOnlyUse - Return true if this instruction will be deleted if we stop using
410// it.
411static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000412 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000413}
414
Chris Lattner4cb170c2004-02-23 06:38:22 +0000415// getPromotedType - Return the specified type promoted as it would be to pass
416// though a va_arg area...
417static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000418 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419 if (ITy->getBitWidth() < 32)
420 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000421 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000422 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000423}
424
Reid Spencer3da59db2006-11-27 01:05:10 +0000425/// getBitCastOperand - If the specified operand is a CastInst or a constant
426/// expression bitcast, return the operand value, otherwise return null.
427static Value *getBitCastOperand(Value *V) {
428 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000429 return I->getOperand(0);
430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000432 return CE->getOperand(0);
433 return 0;
434}
435
Reid Spencer3da59db2006-11-27 01:05:10 +0000436/// This function is a wrapper around CastInst::isEliminableCastPair. It
437/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000438static Instruction::CastOps
439isEliminableCastPair(
440 const CastInst *CI, ///< The first cast instruction
441 unsigned opcode, ///< The opcode of the second cast instruction
442 const Type *DstTy, ///< The target type for the second cast instruction
443 TargetData *TD ///< The target data for pointer size
444) {
445
446 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
447 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 // Get the opcodes of the two Cast instructions
450 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000452
Reid Spencer3da59db2006-11-27 01:05:10 +0000453 return Instruction::CastOps(
454 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000456}
457
458/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459/// in any code being generated. It does not require codegen if V is simple
460/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000461static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
462 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000463 if (V->getType() == Ty || isa<Constant>(V)) return false;
464
Chris Lattner01575b72006-05-25 23:24:33 +0000465 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000466 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000467 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000468 return false;
469 return true;
470}
471
472/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473/// InsertBefore instruction. This is specialized a bit to avoid inserting
474/// casts that are known to not do anything...
475///
Reid Spencer17212df2006-12-12 09:18:51 +0000476Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000478 Instruction *InsertBefore) {
479 if (V->getType() == DestTy) return V;
480 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000481 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000482
Reid Spencer17212df2006-12-12 09:18:51 +0000483 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000484}
485
Chris Lattner4f98c562003-03-10 21:43:22 +0000486// SimplifyCommutative - This performs a few simplifications for commutative
487// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000488//
Chris Lattner4f98c562003-03-10 21:43:22 +0000489// 1. Order operands such that they are listed from right (least complex) to
490// left (most complex). This puts constants before unary operators before
491// binary operators.
492//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000493// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000495//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000496bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000497 bool Changed = false;
498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000500
Chris Lattner4f98c562003-03-10 21:43:22 +0000501 if (!I.isAssociative()) return Changed;
502 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(),
507 cast<Constant>(I.getOperand(1)),
508 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000509 I.setOperand(0, Op->getOperand(0));
510 I.setOperand(1, Folded);
511 return true;
512 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514 isOnlyUse(Op) && isOnlyUse(Op1)) {
515 Constant *C1 = cast<Constant>(Op->getOperand(1));
516 Constant *C2 = cast<Constant>(Op1->getOperand(1));
517
518 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000520 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 Op1->getOperand(0),
522 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000523 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524 I.setOperand(0, New);
525 I.setOperand(1, Folded);
526 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000527 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000530}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000531
Reid Spencere4d87aa2006-12-23 06:05:41 +0000532/// SimplifyCompare - For a CmpInst this function just orders the operands
533/// so that theyare listed from right (least complex) to left (most complex).
534/// This puts constants before unary operators before binary operators.
535bool InstCombiner::SimplifyCompare(CmpInst &I) {
536 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
537 return false;
538 I.swapOperands();
539 // Compare instructions are not associative so there's nothing else we can do.
540 return true;
541}
542
Chris Lattner8d969642003-03-10 23:06:50 +0000543// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000545//
Chris Lattner8d969642003-03-10 23:06:50 +0000546static inline Value *dyn_castNegVal(Value *V) {
547 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000548 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000549
Chris Lattner0ce85802004-12-14 20:08:06 +0000550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000553
554 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555 if (C->getType()->getElementType()->isInteger())
556 return ConstantExpr::getNeg(C);
557
Chris Lattner8d969642003-03-10 23:06:50 +0000558 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000559}
560
Chris Lattner8d969642003-03-10 23:06:50 +0000561static inline Value *dyn_castNotVal(Value *V) {
562 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000563 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000564
565 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000567 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000568 return 0;
569}
570
Chris Lattnerc8802d22003-03-11 00:12:48 +0000571// dyn_castFoldableMul - If this value is a multiply that can be folded into
572// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000573// non-constant operand of the multiply, and set CST to point to the multiplier.
574// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575//
Chris Lattner50af16a2004-11-13 19:50:12 +0000576static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000577 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000578 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000580 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000582 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000583 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000584 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000585 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000586 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000587 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000588 return I->getOperand(0);
589 }
590 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000592}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000593
Chris Lattner574da9b2005-01-13 20:14:25 +0000594/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595/// expression, return it.
596static User *dyn_castGetElementPtr(Value *V) {
597 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599 if (CE->getOpcode() == Instruction::GetElementPtr)
600 return cast<User>(V);
601 return false;
602}
603
Dan Gohmaneee962e2008-04-10 18:43:06 +0000604/// getOpcode - If this is an Instruction or a ConstantExpr, return the
605/// opcode value. Otherwise return UserOp1.
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000606static unsigned getOpcode(const Value *V) {
607 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000608 return I->getOpcode();
Dan Gohmanb99e2e22008-05-29 19:53:46 +0000609 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000610 return CE->getOpcode();
611 // Use UserOp1 to mean there's no opcode.
612 return Instruction::UserOp1;
613}
614
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000616static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000617 APInt Val(C->getValue());
618 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000619}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000620/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000621static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000622 APInt Val(C->getValue());
623 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000624}
625/// Add - Add two ConstantInts together
626static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() + C2->getValue());
628}
629/// And - Bitwise AND two ConstantInts together
630static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631 return ConstantInt::get(C1->getValue() & C2->getValue());
632}
633/// Subtract - Subtract one ConstantInt from another
634static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() - C2->getValue());
636}
637/// Multiply - Multiply two ConstantInts together
638static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Chris Lattner955f3312004-09-28 21:48:02 +0000663
Chris Lattner68d5ff22006-02-09 07:38:58 +0000664/// ComputeMaskedBits - Determine which of the bits specified in Mask are
665/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000666/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
667/// processing.
668/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
669/// we cannot optimize based on the assumption that it is zero without changing
670/// it to be an explicit zero. If we don't change it to zero, other code could
671/// optimized based on the contradictory assumption that it is non-zero.
672/// Because instcombine aggressively folds operations with undef args anyway,
673/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000674void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675 APInt& KnownZero, APInt& KnownOne,
Dan Gohman45b4e482008-05-19 22:14:15 +0000676 unsigned Depth) const {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000677 assert(V && "No Value?");
678 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000680 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681 "Not integer or pointer type!");
682 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683 (!isa<IntegerType>(V->getType()) ||
684 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000685 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000686 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000687 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman45b4e482008-05-19 22:14:15 +0000688
Reid Spencer3e7594f2007-03-08 01:46:38 +0000689 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000691 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000692 KnownZero = ~KnownOne & Mask;
693 return;
694 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000695 // Null is all-zeros.
696 if (isa<ConstantPointerNull>(V)) {
697 KnownOne.clear();
698 KnownZero = Mask;
699 return;
700 }
701 // The address of an aligned GlobalValue has trailing zeros.
702 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703 unsigned Align = GV->getAlignment();
704 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
705 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
706 if (Align > 0)
707 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708 CountTrailingZeros_32(Align));
709 else
710 KnownZero.clear();
711 KnownOne.clear();
712 return;
713 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000714
Dan Gohman23e8b712008-04-28 17:02:21 +0000715 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
716
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 if (Depth == 6 || Mask == 0)
718 return; // Limit search depth.
719
Dan Gohmaneee962e2008-04-10 18:43:06 +0000720 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 if (!I) return;
722
723 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000724 switch (getOpcode(I)) {
725 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000726 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000727 // If either the LHS or the RHS are Zero, the result is zero.
728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000729 APInt Mask2(Mask & ~KnownZero);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733
734 // Output known-1 bits are only known if set in both the LHS & RHS.
735 KnownOne &= KnownOne2;
736 // Output known-0 are known to be clear if zero in either the LHS | RHS.
737 KnownZero |= KnownZero2;
738 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000739 }
740 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000742 APInt Mask2(Mask & ~KnownOne);
743 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746
747 // Output known-0 bits are only known if clear in both the LHS & RHS.
748 KnownZero &= KnownZero2;
749 // Output known-1 are known to be set if set in either the LHS | RHS.
750 KnownOne |= KnownOne2;
751 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000752 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000753 case Instruction::Xor: {
754 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
758
759 // Output known-0 bits are known if clear or set in both the LHS & RHS.
760 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761 // Output known-1 are known to be set if set in only one of the LHS, RHS.
762 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763 KnownZero = KnownZeroOut;
764 return;
765 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000766 case Instruction::Mul: {
767 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
772
773 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000774 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000775 // More trickiness is possible, but this is sufficient for the
776 // interesting case of alignment computation.
777 KnownOne.clear();
778 unsigned TrailZ = KnownZero.countTrailingOnes() +
779 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000780 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000781 KnownZero2.countLeadingOnes(),
782 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000783
Dan Gohmaneee962e2008-04-10 18:43:06 +0000784 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 LeadZ = std::min(LeadZ, BitWidth);
786 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000788 KnownZero &= Mask;
789 return;
790 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000791 case Instruction::UDiv: {
792 // For the purposes of computing leading zeros we can conservatively
793 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000794 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000795 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796 ComputeMaskedBits(I->getOperand(0),
797 AllOnes, KnownZero2, KnownOne2, Depth+1);
798 unsigned LeadZ = KnownZero2.countLeadingOnes();
799
800 KnownOne2.clear();
801 KnownZero2.clear();
802 ComputeMaskedBits(I->getOperand(1),
803 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000804 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805 if (RHSUnknownLeadingOnes != BitWidth)
806 LeadZ = std::min(BitWidth,
807 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000808
809 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
810 return;
811 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 case Instruction::Select:
813 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
816 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
817
818 // Only known if known in both the LHS and RHS.
819 KnownOne &= KnownOne2;
820 KnownZero &= KnownZero2;
821 return;
822 case Instruction::FPTrunc:
823 case Instruction::FPExt:
824 case Instruction::FPToUI:
825 case Instruction::FPToSI:
826 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000827 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000828 return; // Can't work with floating point.
829 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000831 // We can't handle these if we don't know the pointer size.
832 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000833 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000834 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000835 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000836 // Note that we handle pointer operands here because of inttoptr/ptrtoint
837 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000838 const Type *SrcTy = I->getOperand(0)->getType();
839 uint32_t SrcBitWidth = TD ?
840 TD->getTypeSizeInBits(SrcTy) :
841 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000842 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000843 MaskIn.zextOrTrunc(SrcBitWidth);
844 KnownZero.zextOrTrunc(SrcBitWidth);
845 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000846 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000847 KnownZero.zextOrTrunc(BitWidth);
848 KnownOne.zextOrTrunc(BitWidth);
849 // Any top bits are known to be zero.
850 if (BitWidth > SrcBitWidth)
851 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000852 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000853 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000854 case Instruction::BitCast: {
855 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000856 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000857 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
858 return;
859 }
860 break;
861 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000862 case Instruction::SExt: {
863 // Compute the bits in the result that are not present in the input.
864 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000865 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000866
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 APInt MaskIn(Mask);
868 MaskIn.trunc(SrcBitWidth);
869 KnownZero.trunc(SrcBitWidth);
870 KnownOne.trunc(SrcBitWidth);
871 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000873 KnownZero.zext(BitWidth);
874 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000875
876 // If the sign bit of the input is known set or clear, then we know the
877 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000878 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000879 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000880 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000881 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000882 return;
883 }
884 case Instruction::Shl:
885 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
886 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000887 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000888 APInt Mask2(Mask.lshr(ShiftAmt));
889 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000891 KnownZero <<= ShiftAmt;
892 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000893 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000894 return;
895 }
896 break;
897 case Instruction::LShr:
898 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
899 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000901 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000902
903 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000904 APInt Mask2(Mask.shl(ShiftAmt));
905 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000906 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
907 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000909 // high bits known zero.
910 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911 return;
912 }
913 break;
914 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000915 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000916 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000918 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000919
920 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000921 APInt Mask2(Mask.shl(ShiftAmt));
922 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
926
Zhou Shengaa305ab2007-03-28 02:19:03 +0000927 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000929 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000930 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000931 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000932 return;
933 }
934 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000935 case Instruction::Sub: {
936 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937 // We know that the top bits of C-X are clear if X contains less bits
938 // than C (i.e. no wrap-around can happen). For example, 20-X is
939 // positive if we can prove that X is >= 0 and < 16.
940 if (!CLHS->getValue().isNegative()) {
941 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942 // NLZ can't be BitWidth with no sign bit
943 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000944 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
945 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000946
Dan Gohman23e8b712008-04-28 17:02:21 +0000947 // If all of the MaskV bits are known to be zero, then we know the
948 // output top bits are zero, because we now know that the output is
949 // from [0-C].
950 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000951 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952 // Top bits known zero.
953 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000954 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000955 }
956 }
957 }
958 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000959 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000960 // Output known-0 bits are known if clear or set in both the low clear bits
961 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
962 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000963 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
966 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
967
968 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 KnownZeroOut = std::min(KnownZeroOut,
971 KnownZero2.countTrailingOnes());
972
973 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000974 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000975 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000976 case Instruction::SRem:
977 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978 APInt RA = Rem->getValue();
979 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000980 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000981 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
983
984 // The sign of a remainder is equal to the sign of the first
985 // operand (zero being positive).
986 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987 KnownZero2 |= ~LowBits;
988 else if (KnownOne2[BitWidth-1])
989 KnownOne2 |= ~LowBits;
990
991 KnownZero |= KnownZero2 & Mask;
992 KnownOne |= KnownOne2 & Mask;
993
994 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
995 }
996 }
997 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000998 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000999 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001001 if (RA.isPowerOf2()) {
1002 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 APInt Mask2 = LowBits & Mask;
1004 KnownZero |= ~LowBits & Mask;
1005 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001007 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001008 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001009 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001010
1011 // Since the result is less than or equal to either operand, any leading
1012 // zero bits in either operand must also exist in the result.
1013 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1015 Depth+1);
1016 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1017 Depth+1);
1018
1019 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020 KnownZero2.countLeadingOnes());
1021 KnownOne.clear();
1022 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001023 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001024 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001025
1026 case Instruction::Alloca:
1027 case Instruction::Malloc: {
1028 AllocationInst *AI = cast<AllocationInst>(V);
1029 unsigned Align = AI->getAlignment();
1030 if (Align == 0 && TD) {
1031 if (isa<AllocaInst>(AI))
1032 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033 else if (isa<MallocInst>(AI)) {
1034 // Malloc returns maximally aligned memory.
1035 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1036 Align =
1037 std::max(Align,
1038 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1039 Align =
1040 std::max(Align,
1041 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1042 }
1043 }
1044
1045 if (Align > 0)
1046 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047 CountTrailingZeros_32(Align));
1048 break;
1049 }
1050 case Instruction::GetElementPtr: {
1051 // Analyze all of the subscripts of this getelementptr instruction
1052 // to determine if we can prove known low zero bits.
1053 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055 ComputeMaskedBits(I->getOperand(0), LocalMask,
1056 LocalKnownZero, LocalKnownOne, Depth+1);
1057 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1058
1059 gep_type_iterator GTI = gep_type_begin(I);
1060 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061 Value *Index = I->getOperand(i);
1062 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063 // Handle struct member offset arithmetic.
1064 if (!TD) return;
1065 const StructLayout *SL = TD->getStructLayout(STy);
1066 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067 uint64_t Offset = SL->getElementOffset(Idx);
1068 TrailZ = std::min(TrailZ,
1069 CountTrailingZeros_64(Offset));
1070 } else {
1071 // Handle array index arithmetic.
1072 const Type *IndexedTy = GTI.getIndexedType();
1073 if (!IndexedTy->isSized()) return;
1074 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078 ComputeMaskedBits(Index, LocalMask,
1079 LocalKnownZero, LocalKnownOne, Depth+1);
1080 TrailZ = std::min(TrailZ,
1081 CountTrailingZeros_64(TypeSize) +
1082 LocalKnownZero.countTrailingOnes());
1083 }
1084 }
1085
1086 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1087 break;
1088 }
1089 case Instruction::PHI: {
1090 PHINode *P = cast<PHINode>(I);
1091 // Handle the case of a simple two-predecessor recurrence PHI.
1092 // There's a lot more that could theoretically be done here, but
1093 // this is sufficient to catch some interesting cases.
1094 if (P->getNumIncomingValues() == 2) {
1095 for (unsigned i = 0; i != 2; ++i) {
1096 Value *L = P->getIncomingValue(i);
1097 Value *R = P->getIncomingValue(!i);
1098 User *LU = dyn_cast<User>(L);
Matthijs Kooijman214142c2008-05-23 16:17:48 +00001099 if (!LU)
1100 continue;
1101 unsigned Opcode = getOpcode(LU);
Dan Gohmaneee962e2008-04-10 18:43:06 +00001102 // Check for operations that have the property that if
1103 // both their operands have low zero bits, the result
1104 // will have low zero bits.
1105 if (Opcode == Instruction::Add ||
1106 Opcode == Instruction::Sub ||
1107 Opcode == Instruction::And ||
1108 Opcode == Instruction::Or ||
1109 Opcode == Instruction::Mul) {
1110 Value *LL = LU->getOperand(0);
1111 Value *LR = LU->getOperand(1);
1112 // Find a recurrence.
1113 if (LL == I)
1114 L = LR;
1115 else if (LR == I)
1116 L = LL;
1117 else
1118 break;
1119 // Ok, we have a PHI of the form L op= R. Check for low
1120 // zero bits.
1121 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123 Mask2 = APInt::getLowBitsSet(BitWidth,
1124 KnownZero2.countTrailingOnes());
1125 KnownOne2.clear();
1126 KnownZero2.clear();
1127 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1128 KnownZero = Mask &
1129 APInt::getLowBitsSet(BitWidth,
1130 KnownZero2.countTrailingOnes());
1131 break;
1132 }
1133 }
1134 }
1135 break;
1136 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001137 case Instruction::Call:
1138 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139 switch (II->getIntrinsicID()) {
1140 default: break;
1141 case Intrinsic::ctpop:
1142 case Intrinsic::ctlz:
1143 case Intrinsic::cttz: {
1144 unsigned LowBits = Log2_32(BitWidth)+1;
1145 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1146 break;
1147 }
1148 }
1149 }
1150 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001151 }
1152}
1153
Reid Spencere7816b52007-03-08 01:52:58 +00001154/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1155/// this predicate to simplify operations downstream. Mask is known to be zero
1156/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001157bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1158 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001159 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001160 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1162 return (KnownZero & Mask) == Mask;
1163}
1164
Chris Lattner255d8912006-02-11 09:31:47 +00001165/// ShrinkDemandedConstant - Check to see if the specified operand of the
1166/// specified instruction is a constant integer. If so, check to see if there
1167/// are any bits set in the constant that are not demanded. If so, shrink the
1168/// constant and return true.
1169static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001170 APInt Demanded) {
1171 assert(I && "No instruction?");
1172 assert(OpNo < I->getNumOperands() && "Operand index too large");
1173
1174 // If the operand is not a constant integer, nothing to do.
1175 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176 if (!OpC) return false;
1177
1178 // If there are no bits set that aren't demanded, nothing to do.
1179 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180 if ((~Demanded & OpC->getValue()) == 0)
1181 return false;
1182
1183 // This instruction is producing bits that are not demanded. Shrink the RHS.
1184 Demanded &= OpC->getValue();
1185 I->setOperand(OpNo, ConstantInt::get(Demanded));
1186 return true;
1187}
1188
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001189// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1190// set of known zero and one bits, compute the maximum and minimum values that
1191// could have the specified known zero and known one bits, returning them in
1192// min/max.
1193static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001194 const APInt& KnownZero,
1195 const APInt& KnownOne,
1196 APInt& Min, APInt& Max) {
1197 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198 assert(KnownZero.getBitWidth() == BitWidth &&
1199 KnownOne.getBitWidth() == BitWidth &&
1200 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001202 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001203
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001204 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205 // bit if it is unknown.
1206 Min = KnownOne;
1207 Max = KnownOne|UnknownBits;
1208
Zhou Sheng4acf1552007-03-28 05:15:57 +00001209 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001210 Min.set(BitWidth-1);
1211 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001212 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001213}
1214
1215// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216// a set of known zero and one bits, compute the maximum and minimum values that
1217// could have the specified known zero and known one bits, returning them in
1218// min/max.
1219static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001220 const APInt &KnownZero,
1221 const APInt &KnownOne,
1222 APInt &Min, APInt &Max) {
1223 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001224 assert(KnownZero.getBitWidth() == BitWidth &&
1225 KnownOne.getBitWidth() == BitWidth &&
1226 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001228 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001229
1230 // The minimum value is when the unknown bits are all zeros.
1231 Min = KnownOne;
1232 // The maximum value is when the unknown bits are all ones.
1233 Max = KnownOne|UnknownBits;
1234}
Chris Lattner255d8912006-02-11 09:31:47 +00001235
Reid Spencer8cb68342007-03-12 17:25:59 +00001236/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237/// value based on the demanded bits. When this function is called, it is known
1238/// that only the bits set in DemandedMask of the result of V are ever used
1239/// downstream. Consequently, depending on the mask and V, it may be possible
1240/// to replace V with a constant or one of its operands. In such cases, this
1241/// function does the replacement and returns true. In all other cases, it
1242/// returns false after analyzing the expression and setting KnownOne and known
1243/// to be one in the expression. KnownZero contains all the bits that are known
1244/// to be zero in the expression. These are provided to potentially allow the
1245/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246/// the expression. KnownOne and KnownZero always follow the invariant that
1247/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250/// and KnownOne must all be the same.
1251bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252 APInt& KnownZero, APInt& KnownOne,
1253 unsigned Depth) {
1254 assert(V != 0 && "Null pointer of Value???");
1255 assert(Depth <= 6 && "Limit Search Depth");
1256 uint32_t BitWidth = DemandedMask.getBitWidth();
1257 const IntegerType *VTy = cast<IntegerType>(V->getType());
1258 assert(VTy->getBitWidth() == BitWidth &&
1259 KnownZero.getBitWidth() == BitWidth &&
1260 KnownOne.getBitWidth() == BitWidth &&
1261 "Value *V, DemandedMask, KnownZero and KnownOne \
1262 must have same BitWidth");
1263 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264 // We know all of the bits for a constant!
1265 KnownOne = CI->getValue() & DemandedMask;
1266 KnownZero = ~KnownOne & DemandedMask;
1267 return false;
1268 }
1269
Zhou Sheng96704452007-03-14 03:21:24 +00001270 KnownZero.clear();
1271 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 if (!V->hasOneUse()) { // Other users may use these bits.
1273 if (Depth != 0) { // Not at the root.
1274 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1276 return false;
1277 }
1278 // If this is the root being simplified, allow it to have multiple uses,
1279 // just set the DemandedMask to all bits.
1280 DemandedMask = APInt::getAllOnesValue(BitWidth);
1281 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1282 if (V != UndefValue::get(VTy))
1283 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1284 return false;
1285 } else if (Depth == 6) { // Limit search depth.
1286 return false;
1287 }
1288
1289 Instruction *I = dyn_cast<Instruction>(V);
1290 if (!I) return false; // Only analyze instructions.
1291
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001295 default:
1296 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1297 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 case Instruction::And:
1299 // If either the LHS or the RHS are Zero, the result is zero.
1300 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301 RHSKnownZero, RHSKnownOne, Depth+1))
1302 return true;
1303 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1305
1306 // If something is known zero on the RHS, the bits aren't demanded on the
1307 // LHS.
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309 LHSKnownZero, LHSKnownOne, Depth+1))
1310 return true;
1311 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313
1314 // If all of the demanded bits are known 1 on one side, return the other.
1315 // These bits cannot contribute to the result of the 'and'.
1316 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1317 (DemandedMask & ~LHSKnownZero))
1318 return UpdateValueUsesWith(I, I->getOperand(0));
1319 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1320 (DemandedMask & ~RHSKnownZero))
1321 return UpdateValueUsesWith(I, I->getOperand(1));
1322
1323 // If all of the demanded bits in the inputs are known zeros, return zero.
1324 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1326
1327 // If the RHS is a constant, see if we can simplify it.
1328 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329 return UpdateValueUsesWith(I, I);
1330
1331 // Output known-1 bits are only known if set in both the LHS & RHS.
1332 RHSKnownOne &= LHSKnownOne;
1333 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334 RHSKnownZero |= LHSKnownZero;
1335 break;
1336 case Instruction::Or:
1337 // If either the LHS or the RHS are One, the result is One.
1338 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1339 RHSKnownZero, RHSKnownOne, Depth+1))
1340 return true;
1341 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343 // If something is known one on the RHS, the bits aren't demanded on the
1344 // LHS.
1345 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1346 LHSKnownZero, LHSKnownOne, Depth+1))
1347 return true;
1348 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1349 "Bits known to be one AND zero?");
1350
1351 // If all of the demanded bits are known zero on one side, return the other.
1352 // These bits cannot contribute to the result of the 'or'.
1353 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1354 (DemandedMask & ~LHSKnownOne))
1355 return UpdateValueUsesWith(I, I->getOperand(0));
1356 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1357 (DemandedMask & ~RHSKnownOne))
1358 return UpdateValueUsesWith(I, I->getOperand(1));
1359
1360 // If all of the potentially set bits on one side are known to be set on
1361 // the other side, just use the 'other' side.
1362 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1363 (DemandedMask & (~RHSKnownZero)))
1364 return UpdateValueUsesWith(I, I->getOperand(0));
1365 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1366 (DemandedMask & (~LHSKnownZero)))
1367 return UpdateValueUsesWith(I, I->getOperand(1));
1368
1369 // If the RHS is a constant, see if we can simplify it.
1370 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371 return UpdateValueUsesWith(I, I);
1372
1373 // Output known-0 bits are only known if clear in both the LHS & RHS.
1374 RHSKnownZero &= LHSKnownZero;
1375 // Output known-1 are known to be set if set in either the LHS | RHS.
1376 RHSKnownOne |= LHSKnownOne;
1377 break;
1378 case Instruction::Xor: {
1379 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380 RHSKnownZero, RHSKnownOne, Depth+1))
1381 return true;
1382 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1383 "Bits known to be one AND zero?");
1384 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1385 LHSKnownZero, LHSKnownOne, Depth+1))
1386 return true;
1387 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1388 "Bits known to be one AND zero?");
1389
1390 // If all of the demanded bits are known zero on one side, return the other.
1391 // These bits cannot contribute to the result of the 'xor'.
1392 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393 return UpdateValueUsesWith(I, I->getOperand(0));
1394 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395 return UpdateValueUsesWith(I, I->getOperand(1));
1396
1397 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1399 (RHSKnownOne & LHSKnownOne);
1400 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1402 (RHSKnownOne & LHSKnownZero);
1403
1404 // If all of the demanded bits are known to be zero on one side or the
1405 // other, turn this into an *inclusive* or.
1406 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1408 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001409 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 I->getName());
1411 InsertNewInstBefore(Or, *I);
1412 return UpdateValueUsesWith(I, Or);
1413 }
1414
1415 // If all of the demanded bits on one side are known, and all of the set
1416 // bits on that side are also known to be set on the other side, turn this
1417 // into an AND, as we know the bits will be cleared.
1418 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1420 // all known
1421 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1423 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001424 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 InsertNewInstBefore(And, *I);
1426 return UpdateValueUsesWith(I, And);
1427 }
1428 }
1429
1430 // If the RHS is a constant, see if we can simplify it.
1431 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433 return UpdateValueUsesWith(I, I);
1434
1435 RHSKnownZero = KnownZeroOut;
1436 RHSKnownOne = KnownOneOut;
1437 break;
1438 }
1439 case Instruction::Select:
1440 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441 RHSKnownZero, RHSKnownOne, Depth+1))
1442 return true;
1443 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1444 LHSKnownZero, LHSKnownOne, Depth+1))
1445 return true;
1446 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1447 "Bits known to be one AND zero?");
1448 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1449 "Bits known to be one AND zero?");
1450
1451 // If the operands are constants, see if we can simplify them.
1452 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453 return UpdateValueUsesWith(I, I);
1454 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455 return UpdateValueUsesWith(I, I);
1456
1457 // Only known if known in both the LHS and RHS.
1458 RHSKnownOne &= LHSKnownOne;
1459 RHSKnownZero &= LHSKnownZero;
1460 break;
1461 case Instruction::Trunc: {
1462 uint32_t truncBf =
1463 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001464 DemandedMask.zext(truncBf);
1465 RHSKnownZero.zext(truncBf);
1466 RHSKnownOne.zext(truncBf);
1467 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001469 return true;
1470 DemandedMask.trunc(BitWidth);
1471 RHSKnownZero.trunc(BitWidth);
1472 RHSKnownOne.trunc(BitWidth);
1473 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1474 "Bits known to be one AND zero?");
1475 break;
1476 }
1477 case Instruction::BitCast:
1478 if (!I->getOperand(0)->getType()->isInteger())
1479 return false;
1480
1481 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482 RHSKnownZero, RHSKnownOne, Depth+1))
1483 return true;
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 break;
1487 case Instruction::ZExt: {
1488 // Compute the bits in the result that are not present in the input.
1489 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001490 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001491
Zhou Shengd48653a2007-03-29 04:45:55 +00001492 DemandedMask.trunc(SrcBitWidth);
1493 RHSKnownZero.trunc(SrcBitWidth);
1494 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001495 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001497 return true;
1498 DemandedMask.zext(BitWidth);
1499 RHSKnownZero.zext(BitWidth);
1500 RHSKnownOne.zext(BitWidth);
1501 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1502 "Bits known to be one AND zero?");
1503 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001504 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001505 break;
1506 }
1507 case Instruction::SExt: {
1508 // Compute the bits in the result that are not present in the input.
1509 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001510 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001511
Reid Spencer8cb68342007-03-12 17:25:59 +00001512 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001513 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001514
Zhou Sheng01542f32007-03-29 02:26:30 +00001515 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001516 // If any of the sign extended bits are demanded, we know that the sign
1517 // bit is demanded.
1518 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001519 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001520
Zhou Shengd48653a2007-03-29 04:45:55 +00001521 InputDemandedBits.trunc(SrcBitWidth);
1522 RHSKnownZero.trunc(SrcBitWidth);
1523 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001524 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001526 return true;
1527 InputDemandedBits.zext(BitWidth);
1528 RHSKnownZero.zext(BitWidth);
1529 RHSKnownOne.zext(BitWidth);
1530 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1531 "Bits known to be one AND zero?");
1532
1533 // If the sign bit of the input is known set or clear, then we know the
1534 // top bits of the result.
1535
1536 // If the input sign bit is known zero, or if the NewBits are not demanded
1537 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001538 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001539 {
1540 // Convert to ZExt cast
1541 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001543 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001544 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001545 }
1546 break;
1547 }
1548 case Instruction::Add: {
1549 // Figure out what the input bits are. If the top bits of the and result
1550 // are not demanded, then the add doesn't demand them from its input
1551 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001552 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001553
1554 // If there is a constant on the RHS, there are a variety of xformations
1555 // we can do.
1556 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557 // If null, this should be simplified elsewhere. Some of the xforms here
1558 // won't work if the RHS is zero.
1559 if (RHS->isZero())
1560 break;
1561
1562 // If the top bit of the output is demanded, demand everything from the
1563 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001564 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001565
1566 // Find information about known zero/one bits in the input.
1567 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1568 LHSKnownZero, LHSKnownOne, Depth+1))
1569 return true;
1570
1571 // If the RHS of the add has bits set that can't affect the input, reduce
1572 // the constant.
1573 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574 return UpdateValueUsesWith(I, I);
1575
1576 // Avoid excess work.
1577 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1578 break;
1579
1580 // Turn it into OR if input bits are zero.
1581 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1582 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001583 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001584 I->getName());
1585 InsertNewInstBefore(Or, *I);
1586 return UpdateValueUsesWith(I, Or);
1587 }
1588
1589 // We can say something about the output known-zero and known-one bits,
1590 // depending on potential carries from the input constant and the
1591 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1592 // bits set and the RHS constant is 0x01001, then we know we have a known
1593 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1594
1595 // To compute this, we first compute the potential carry bits. These are
1596 // the bits which may be modified. I'm not aware of a better way to do
1597 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001598 const APInt& RHSVal = RHS->getValue();
1599 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001600
1601 // Now that we know which bits have carries, compute the known-1/0 sets.
1602
1603 // Bits are known one if they are known zero in one operand and one in the
1604 // other, and there is no input carry.
1605 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1606 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1607
1608 // Bits are known zero if they are known zero in both operands and there
1609 // is no input carry.
1610 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1611 } else {
1612 // If the high-bits of this ADD are not demanded, then it does not demand
1613 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001614 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001615 // Right fill the mask of bits for this ADD to demand the most
1616 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001617 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001618 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619 LHSKnownZero, LHSKnownOne, Depth+1))
1620 return true;
1621 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622 LHSKnownZero, LHSKnownOne, Depth+1))
1623 return true;
1624 }
1625 }
1626 break;
1627 }
1628 case Instruction::Sub:
1629 // If the high-bits of this SUB are not demanded, then it does not demand
1630 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001631 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001632 // Right fill the mask of bits for this SUB to demand the most
1633 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001634 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001635 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001636 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637 LHSKnownZero, LHSKnownOne, Depth+1))
1638 return true;
1639 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640 LHSKnownZero, LHSKnownOne, Depth+1))
1641 return true;
1642 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001643 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644 // the known zeros and ones.
1645 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001646 break;
1647 case Instruction::Shl:
1648 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001649 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001650 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001652 RHSKnownZero, RHSKnownOne, Depth+1))
1653 return true;
1654 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1655 "Bits known to be one AND zero?");
1656 RHSKnownZero <<= ShiftAmt;
1657 RHSKnownOne <<= ShiftAmt;
1658 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001659 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001660 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 }
1662 break;
1663 case Instruction::LShr:
1664 // For a logical shift right
1665 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001666 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001667
Reid Spencer8cb68342007-03-12 17:25:59 +00001668 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001669 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001671 RHSKnownZero, RHSKnownOne, Depth+1))
1672 return true;
1673 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1674 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001675 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001677 if (ShiftAmt) {
1678 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001679 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001680 RHSKnownZero |= HighBits; // high bits known zero.
1681 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001682 }
1683 break;
1684 case Instruction::AShr:
1685 // If this is an arithmetic shift right and only the low-bit is set, we can
1686 // always convert this into a logical shr, even if the shift amount is
1687 // variable. The low bit of the shift cannot be an input sign bit unless
1688 // the shift amount is >= the size of the datatype, which is undefined.
1689 if (DemandedMask == 1) {
1690 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001691 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001692 I->getOperand(0), I->getOperand(1), I->getName());
1693 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694 return UpdateValueUsesWith(I, NewVal);
1695 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001696
1697 // If the sign bit is the only bit demanded by this ashr, then there is no
1698 // need to do it, the shift doesn't change the high bit.
1699 if (DemandedMask.isSignBit())
1700 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001701
1702 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001703 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001704
Reid Spencer8cb68342007-03-12 17:25:59 +00001705 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001706 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001707 // If any of the "high bits" are demanded, we should set the sign bit as
1708 // demanded.
1709 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001711 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001712 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001713 RHSKnownZero, RHSKnownOne, Depth+1))
1714 return true;
1715 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1716 "Bits known to be one AND zero?");
1717 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001718 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001719 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1721
1722 // Handle the sign bits.
1723 APInt SignBit(APInt::getSignBit(BitWidth));
1724 // Adjust to where it is now in the mask.
1725 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1726
1727 // If the input sign bit is known to be zero, or if none of the top bits
1728 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001729 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001730 (HighBits & ~DemandedMask) == HighBits) {
1731 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001732 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001733 I->getOperand(0), SA, I->getName());
1734 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735 return UpdateValueUsesWith(I, NewVal);
1736 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737 RHSKnownOne |= HighBits;
1738 }
1739 }
1740 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001741 case Instruction::SRem:
1742 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743 APInt RA = Rem->getValue();
1744 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001745 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001746 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748 LHSKnownZero, LHSKnownOne, Depth+1))
1749 return true;
1750
1751 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752 LHSKnownZero |= ~LowBits;
1753 else if (LHSKnownOne[BitWidth-1])
1754 LHSKnownOne |= ~LowBits;
1755
1756 KnownZero |= LHSKnownZero & DemandedMask;
1757 KnownOne |= LHSKnownOne & DemandedMask;
1758
1759 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1760 }
1761 }
1762 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001763 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001764 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001766 if (RA.isPowerOf2()) {
1767 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001768 APInt Mask2 = LowBits & DemandedMask;
1769 KnownZero |= ~LowBits & DemandedMask;
1770 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771 KnownZero, KnownOne, Depth+1))
1772 return true;
1773
1774 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001775 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001776 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001777 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001778
1779 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001781 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782 KnownZero2, KnownOne2, Depth+1))
1783 return true;
1784
Dan Gohman23e8b712008-04-28 17:02:21 +00001785 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001786 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001787 KnownZero2, KnownOne2, Depth+1))
1788 return true;
1789
1790 Leaders = std::max(Leaders,
1791 KnownZero2.countLeadingOnes());
1792 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001793 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001794 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001795 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001796
1797 // If the client is only demanding bits that we know, return the known
1798 // constant.
1799 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1801 return false;
1802}
1803
Chris Lattner867b99f2006-10-05 06:55:50 +00001804
1805/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806/// 64 or fewer elements. DemandedElts contains the set of elements that are
1807/// actually used by the caller. This method analyzes which elements of the
1808/// operand are undef and returns that information in UndefElts.
1809///
1810/// If the information about demanded elements can be used to simplify the
1811/// operation, the operation is simplified, then the resultant value is
1812/// returned. This returns null if no change was made.
1813Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814 uint64_t &UndefElts,
1815 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001816 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001817 assert(VWidth <= 64 && "Vector too wide to analyze!");
1818 uint64_t EltMask = ~0ULL >> (64-VWidth);
1819 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820 "Invalid DemandedElts!");
1821
1822 if (isa<UndefValue>(V)) {
1823 // If the entire vector is undefined, just return this info.
1824 UndefElts = EltMask;
1825 return 0;
1826 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827 UndefElts = EltMask;
1828 return UndefValue::get(V->getType());
1829 }
1830
1831 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001832 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001834 Constant *Undef = UndefValue::get(EltTy);
1835
1836 std::vector<Constant*> Elts;
1837 for (unsigned i = 0; i != VWidth; ++i)
1838 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1839 Elts.push_back(Undef);
1840 UndefElts |= (1ULL << i);
1841 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1842 Elts.push_back(Undef);
1843 UndefElts |= (1ULL << i);
1844 } else { // Otherwise, defined.
1845 Elts.push_back(CP->getOperand(i));
1846 }
1847
1848 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001849 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001850 return NewCP != CP ? NewCP : 0;
1851 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001852 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001853 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001854 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001855 Constant *Zero = Constant::getNullValue(EltTy);
1856 Constant *Undef = UndefValue::get(EltTy);
1857 std::vector<Constant*> Elts;
1858 for (unsigned i = 0; i != VWidth; ++i)
1859 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001861 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001862 }
1863
1864 if (!V->hasOneUse()) { // Other users may use these bits.
1865 if (Depth != 0) { // Not at the root.
1866 // TODO: Just compute the UndefElts information recursively.
1867 return false;
1868 }
1869 return false;
1870 } else if (Depth == 10) { // Limit search depth.
1871 return false;
1872 }
1873
1874 Instruction *I = dyn_cast<Instruction>(V);
1875 if (!I) return false; // Only analyze instructions.
1876
1877 bool MadeChange = false;
1878 uint64_t UndefElts2;
1879 Value *TmpV;
1880 switch (I->getOpcode()) {
1881 default: break;
1882
1883 case Instruction::InsertElement: {
1884 // If this is a variable index, we don't know which element it overwrites.
1885 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001886 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001887 if (Idx == 0) {
1888 // Note that we can't propagate undef elt info, because we don't know
1889 // which elt is getting updated.
1890 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891 UndefElts2, Depth+1);
1892 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1893 break;
1894 }
1895
1896 // If this is inserting an element that isn't demanded, remove this
1897 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001898 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001899 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900 return AddSoonDeadInstToWorklist(*I, 0);
1901
1902 // Otherwise, the element inserted overwrites whatever was there, so the
1903 // input demanded set is simpler than the output set.
1904 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905 DemandedElts & ~(1ULL << IdxNo),
1906 UndefElts, Depth+1);
1907 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1908
1909 // The inserted element is defined.
1910 UndefElts |= 1ULL << IdxNo;
1911 break;
1912 }
Chris Lattner69878332007-04-14 22:29:23 +00001913 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001914 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001915 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1916 if (!VTy) break;
1917 unsigned InVWidth = VTy->getNumElements();
1918 uint64_t InputDemandedElts = 0;
1919 unsigned Ratio;
1920
1921 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001922 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001923 // elements as are demanded of us.
1924 Ratio = 1;
1925 InputDemandedElts = DemandedElts;
1926 } else if (VWidth > InVWidth) {
1927 // Untested so far.
1928 break;
1929
1930 // If there are more elements in the result than there are in the source,
1931 // then an input element is live if any of the corresponding output
1932 // elements are live.
1933 Ratio = VWidth/InVWidth;
1934 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935 if (DemandedElts & (1ULL << OutIdx))
1936 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1937 }
1938 } else {
1939 // Untested so far.
1940 break;
1941
1942 // If there are more elements in the source than there are in the result,
1943 // then an input element is live if the corresponding output element is
1944 // live.
1945 Ratio = InVWidth/VWidth;
1946 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947 if (DemandedElts & (1ULL << InIdx/Ratio))
1948 InputDemandedElts |= 1ULL << InIdx;
1949 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001950
Chris Lattner69878332007-04-14 22:29:23 +00001951 // div/rem demand all inputs, because they don't want divide by zero.
1952 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953 UndefElts2, Depth+1);
1954 if (TmpV) {
1955 I->setOperand(0, TmpV);
1956 MadeChange = true;
1957 }
1958
1959 UndefElts = UndefElts2;
1960 if (VWidth > InVWidth) {
1961 assert(0 && "Unimp");
1962 // If there are more elements in the result than there are in the source,
1963 // then an output element is undef if the corresponding input element is
1964 // undef.
1965 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967 UndefElts |= 1ULL << OutIdx;
1968 } else if (VWidth < InVWidth) {
1969 assert(0 && "Unimp");
1970 // If there are more elements in the source than there are in the result,
1971 // then a result element is undef if all of the corresponding input
1972 // elements are undef.
1973 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1974 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1976 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1977 }
1978 break;
1979 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001980 case Instruction::And:
1981 case Instruction::Or:
1982 case Instruction::Xor:
1983 case Instruction::Add:
1984 case Instruction::Sub:
1985 case Instruction::Mul:
1986 // div/rem demand all inputs, because they don't want divide by zero.
1987 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988 UndefElts, Depth+1);
1989 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991 UndefElts2, Depth+1);
1992 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1993
1994 // Output elements are undefined if both are undefined. Consider things
1995 // like undef&0. The result is known zero, not undef.
1996 UndefElts &= UndefElts2;
1997 break;
1998
1999 case Instruction::Call: {
2000 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2001 if (!II) break;
2002 switch (II->getIntrinsicID()) {
2003 default: break;
2004
2005 // Binary vector operations that work column-wise. A dest element is a
2006 // function of the corresponding input elements from the two inputs.
2007 case Intrinsic::x86_sse_sub_ss:
2008 case Intrinsic::x86_sse_mul_ss:
2009 case Intrinsic::x86_sse_min_ss:
2010 case Intrinsic::x86_sse_max_ss:
2011 case Intrinsic::x86_sse2_sub_sd:
2012 case Intrinsic::x86_sse2_mul_sd:
2013 case Intrinsic::x86_sse2_min_sd:
2014 case Intrinsic::x86_sse2_max_sd:
2015 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016 UndefElts, Depth+1);
2017 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019 UndefElts2, Depth+1);
2020 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2021
2022 // If only the low elt is demanded and this is a scalarizable intrinsic,
2023 // scalarize it now.
2024 if (DemandedElts == 1) {
2025 switch (II->getIntrinsicID()) {
2026 default: break;
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse_mul_ss:
2029 case Intrinsic::x86_sse2_sub_sd:
2030 case Intrinsic::x86_sse2_mul_sd:
2031 // TODO: Lower MIN/MAX/ABS/etc
2032 Value *LHS = II->getOperand(1);
2033 Value *RHS = II->getOperand(2);
2034 // Extract the element as scalars.
2035 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2037
2038 switch (II->getIntrinsicID()) {
2039 default: assert(0 && "Case stmts out of sync!");
2040 case Intrinsic::x86_sse_sub_ss:
2041 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002043 II->getName()), *II);
2044 break;
2045 case Intrinsic::x86_sse_mul_ss:
2046 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002047 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002048 II->getName()), *II);
2049 break;
2050 }
2051
2052 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002053 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2054 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002055 InsertNewInstBefore(New, *II);
2056 AddSoonDeadInstToWorklist(*II, 0);
2057 return New;
2058 }
2059 }
2060
2061 // Output elements are undefined if both are undefined. Consider things
2062 // like undef&0. The result is known zero, not undef.
2063 UndefElts &= UndefElts2;
2064 break;
2065 }
2066 break;
2067 }
2068 }
2069 return MadeChange ? I : 0;
2070}
2071
Dan Gohman45b4e482008-05-19 22:14:15 +00002072/// ComputeNumSignBits - Return the number of times the sign bit of the
2073/// register is replicated into the other bits. We know that at least 1 bit
2074/// is always equal to the sign bit (itself), but other cases can give us
2075/// information. For example, immediately after an "ashr X, 2", we know that
2076/// the top 3 bits are all equal to each other, so we return 3.
2077///
2078unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079 const IntegerType *Ty = cast<IntegerType>(V->getType());
2080 unsigned TyBits = Ty->getBitWidth();
2081 unsigned Tmp, Tmp2;
Dan Gohmana332f172008-05-23 02:28:01 +00002082 unsigned FirstAnswer = 1;
Dan Gohman45b4e482008-05-19 22:14:15 +00002083
2084 if (Depth == 6)
2085 return 1; // Limit search depth.
2086
2087 User *U = dyn_cast<User>(V);
2088 switch (getOpcode(V)) {
2089 default: break;
2090 case Instruction::SExt:
2091 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2093
2094 case Instruction::AShr:
2095 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002096 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002097 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098 Tmp += C->getZExtValue();
2099 if (Tmp > TyBits) Tmp = TyBits;
2100 }
2101 return Tmp;
2102 case Instruction::Shl:
2103 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104 // shl destroys sign bits.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106 if (C->getZExtValue() >= TyBits || // Bad shift.
2107 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2108 return Tmp - C->getZExtValue();
2109 }
2110 break;
2111 case Instruction::And:
2112 case Instruction::Or:
Dan Gohmana332f172008-05-23 02:28:01 +00002113 case Instruction::Xor: // NOT is handled here.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002114 // Logical binary ops preserve the number of sign bits at the worst.
2115 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2116 if (Tmp != 1) {
2117 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohmana332f172008-05-23 02:28:01 +00002118 FirstAnswer = std::min(Tmp, Tmp2);
2119 // We computed what we know about the sign bits as our first
2120 // answer. Now proceed to the generic code that uses
2121 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002122 }
Dan Gohmana332f172008-05-23 02:28:01 +00002123 break;
Dan Gohman45b4e482008-05-19 22:14:15 +00002124
2125 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002126 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002127 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002128 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002129 return std::min(Tmp, Tmp2);
2130
2131 case Instruction::Add:
2132 // Add can have at most one carry bit. Thus we know that the output
2133 // is, at worst, one more bit than the inputs.
2134 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135 if (Tmp == 1) return 1; // Early out.
2136
2137 // Special case decrementing a value (ADD X, -1):
2138 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139 if (CRHS->isAllOnesValue()) {
2140 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141 APInt Mask = APInt::getAllOnesValue(TyBits);
2142 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2143
2144 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2145 // sign bits set.
2146 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2147 return TyBits;
2148
2149 // If we are subtracting one from a positive number, there is no carry
2150 // out of the result.
2151 if (KnownZero.isNegative())
2152 return Tmp;
2153 }
2154
2155 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156 if (Tmp2 == 1) return 1;
2157 return std::min(Tmp, Tmp2)-1;
2158 break;
2159
2160 case Instruction::Sub:
2161 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162 if (Tmp2 == 1) return 1;
2163
2164 // Handle NEG.
2165 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166 if (CLHS->isNullValue()) {
2167 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168 APInt Mask = APInt::getAllOnesValue(TyBits);
2169 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2171 // sign bits set.
2172 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2173 return TyBits;
2174
2175 // If the input is known to be positive (the sign bit is known clear),
2176 // the output of the NEG has the same number of sign bits as the input.
2177 if (KnownZero.isNegative())
2178 return Tmp2;
2179
2180 // Otherwise, we treat this like a SUB.
2181 }
2182
2183 // Sub can have at most one carry bit. Thus we know that the output
2184 // is, at worst, one more bit than the inputs.
2185 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186 if (Tmp == 1) return 1; // Early out.
2187 return std::min(Tmp, Tmp2)-1;
2188 break;
2189 case Instruction::Trunc:
2190 // FIXME: it's tricky to do anything useful for this, but it is an important
2191 // case for targets like X86.
2192 break;
2193 }
2194
2195 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196 // use this information.
2197 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198 APInt Mask = APInt::getAllOnesValue(TyBits);
2199 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2200
2201 if (KnownZero.isNegative()) { // sign bit is 0
2202 Mask = KnownZero;
2203 } else if (KnownOne.isNegative()) { // sign bit is 1;
2204 Mask = KnownOne;
2205 } else {
2206 // Nothing known.
Dan Gohmana332f172008-05-23 02:28:01 +00002207 return FirstAnswer;
Dan Gohman45b4e482008-05-19 22:14:15 +00002208 }
2209
2210 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2211 // the number of identical bits in the top of the input value.
2212 Mask = ~Mask;
2213 Mask <<= Mask.getBitWidth()-TyBits;
2214 // Return # leading zeros. We use 'min' here in case Val was zero before
2215 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohmana332f172008-05-23 02:28:01 +00002216 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman45b4e482008-05-19 22:14:15 +00002217}
2218
2219
Chris Lattner564a7272003-08-13 19:01:45 +00002220/// AssociativeOpt - Perform an optimization on an associative operator. This
2221/// function is designed to check a chain of associative operators for a
2222/// potential to apply a certain optimization. Since the optimization may be
2223/// applicable if the expression was reassociated, this checks the chain, then
2224/// reassociates the expression as necessary to expose the optimization
2225/// opportunity. This makes use of a special Functor, which must define
2226/// 'shouldApply' and 'apply' methods.
2227///
2228template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002229static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002230 unsigned Opcode = Root.getOpcode();
2231 Value *LHS = Root.getOperand(0);
2232
2233 // Quick check, see if the immediate LHS matches...
2234 if (F.shouldApply(LHS))
2235 return F.apply(Root);
2236
2237 // Otherwise, if the LHS is not of the same opcode as the root, return.
2238 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002239 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002240 // Should we apply this transform to the RHS?
2241 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2242
2243 // If not to the RHS, check to see if we should apply to the LHS...
2244 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2246 ShouldApply = true;
2247 }
2248
2249 // If the functor wants to apply the optimization to the RHS of LHSI,
2250 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2251 if (ShouldApply) {
2252 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002253
Chris Lattner564a7272003-08-13 19:01:45 +00002254 // Now all of the instructions are in the current basic block, go ahead
2255 // and perform the reassociation.
2256 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2257
2258 // First move the selected RHS to the LHS of the root...
2259 Root.setOperand(0, LHSI->getOperand(1));
2260
2261 // Make what used to be the LHS of the root be the user of the root...
2262 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002263 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002264 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2265 return 0;
2266 }
Chris Lattner65725312004-04-16 18:08:07 +00002267 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002268 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002269 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270 BasicBlock::iterator ARI = &Root; ++ARI;
2271 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2272 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002273
2274 // Now propagate the ExtraOperand down the chain of instructions until we
2275 // get to LHSI.
2276 while (TmpLHSI != LHSI) {
2277 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002278 // Move the instruction to immediately before the chain we are
2279 // constructing to avoid breaking dominance properties.
2280 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281 BB->getInstList().insert(ARI, NextLHSI);
2282 ARI = NextLHSI;
2283
Chris Lattner564a7272003-08-13 19:01:45 +00002284 Value *NextOp = NextLHSI->getOperand(1);
2285 NextLHSI->setOperand(1, ExtraOperand);
2286 TmpLHSI = NextLHSI;
2287 ExtraOperand = NextOp;
2288 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002289
Chris Lattner564a7272003-08-13 19:01:45 +00002290 // Now that the instructions are reassociated, have the functor perform
2291 // the transformation...
2292 return F.apply(Root);
2293 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002294
Chris Lattner564a7272003-08-13 19:01:45 +00002295 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2296 }
2297 return 0;
2298}
2299
Dan Gohman844731a2008-05-13 00:00:25 +00002300namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002301
Nick Lewycky02d639f2008-05-23 04:34:58 +00002302// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002303struct AddRHS {
2304 Value *RHS;
2305 AddRHS(Value *rhs) : RHS(rhs) {}
2306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002308 return BinaryOperator::CreateShl(Add.getOperand(0),
2309 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002310 }
2311};
2312
2313// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2314// iff C1&C2 == 0
2315struct AddMaskingAnd {
2316 Constant *C2;
2317 AddMaskingAnd(Constant *c) : C2(c) {}
2318 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002319 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002320 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002321 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002322 }
2323 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002324 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002325 }
2326};
2327
Dan Gohman844731a2008-05-13 00:00:25 +00002328}
2329
Chris Lattner6e7ba452005-01-01 16:22:27 +00002330static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002331 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002332 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002333 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002334 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002335
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002336 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002337 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002338 }
2339
Chris Lattner2eefe512004-04-09 19:05:30 +00002340 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002341 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002343
Chris Lattner2eefe512004-04-09 19:05:30 +00002344 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2345 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002346 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002348 }
2349
2350 Value *Op0 = SO, *Op1 = ConstOperand;
2351 if (!ConstIsRHS)
2352 std::swap(Op0, Op1);
2353 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002356 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002357 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002358 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002359 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002360 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002361 abort();
2362 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002363 return IC->InsertNewInstBefore(New, I);
2364}
2365
2366// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367// constant as the other operand, try to fold the binary operator into the
2368// select arguments. This also works for Cast instructions, which obviously do
2369// not have a second operand.
2370static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2371 InstCombiner *IC) {
2372 // Don't modify shared select instructions
2373 if (!SI->hasOneUse()) return 0;
2374 Value *TV = SI->getOperand(1);
2375 Value *FV = SI->getOperand(2);
2376
2377 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002378 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002379 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002380
Chris Lattner6e7ba452005-01-01 16:22:27 +00002381 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2383
Gabor Greif051a9502008-04-06 20:25:17 +00002384 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2385 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002386 }
2387 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002388}
2389
Chris Lattner4e998b22004-09-29 05:07:12 +00002390
2391/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392/// node as operand #0, see if we can fold the instruction into the PHI (which
2393/// is only possible if all operands to the PHI are constants).
2394Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002396 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002397 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002398
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002399 // Check to see if all of the operands of the PHI are constants. If there is
2400 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002401 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002402 BasicBlock *NonConstBB = 0;
2403 for (unsigned i = 0; i != NumPHIValues; ++i)
2404 if (!isa<Constant>(PN->getIncomingValue(i))) {
2405 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002406 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002407 NonConstBB = PN->getIncomingBlock(i);
2408
2409 // If the incoming non-constant value is in I's block, we have an infinite
2410 // loop.
2411 if (NonConstBB == I.getParent())
2412 return 0;
2413 }
2414
2415 // If there is exactly one non-constant value, we can insert a copy of the
2416 // operation in that block. However, if this is a critical edge, we would be
2417 // inserting the computation one some other paths (e.g. inside a loop). Only
2418 // do this if the pred block is unconditionally branching into the phi block.
2419 if (NonConstBB) {
2420 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421 if (!BI || !BI->isUnconditional()) return 0;
2422 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002423
2424 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002425 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002426 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002427 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002428 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002429
2430 // Next, add all of the operands to the PHI.
2431 if (I.getNumOperands() == 2) {
2432 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002433 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002434 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002435 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002436 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2438 else
2439 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002440 } else {
2441 assert(PN->getIncomingBlock(i) == NonConstBB);
2442 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002443 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002444 PN->getIncomingValue(i), C, "phitmp",
2445 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002446 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002447 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002448 CI->getPredicate(),
2449 PN->getIncomingValue(i), C, "phitmp",
2450 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002451 else
2452 assert(0 && "Unknown binop!");
2453
Chris Lattnerdbab3862007-03-02 21:28:56 +00002454 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002455 }
2456 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002458 } else {
2459 CastInst *CI = cast<CastInst>(&I);
2460 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002461 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002462 Value *InV;
2463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002464 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002465 } else {
2466 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002467 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002468 I.getType(), "phitmp",
2469 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002470 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002471 }
2472 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002473 }
2474 }
2475 return ReplaceInstUsesWith(I, NewPN);
2476}
2477
Chris Lattner2454a2e2008-01-29 06:52:45 +00002478
2479/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2480/// value is never equal to -0.0.
2481///
2482/// Note that this function will need to be revisited when we support nondefault
2483/// rounding modes!
2484///
2485static bool CannotBeNegativeZero(const Value *V) {
2486 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487 return !CFP->getValueAPF().isNegZero();
2488
Chris Lattner2454a2e2008-01-29 06:52:45 +00002489 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002490 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002491 if (I->getOpcode() == Instruction::Add &&
2492 isa<ConstantFP>(I->getOperand(1)) &&
2493 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2494 return true;
2495
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002496 // sitofp and uitofp turn into +0.0 for zero.
2497 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2498 return true;
2499
Chris Lattner2454a2e2008-01-29 06:52:45 +00002500 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501 if (II->getIntrinsicID() == Intrinsic::sqrt)
2502 return CannotBeNegativeZero(II->getOperand(1));
2503
2504 if (const CallInst *CI = dyn_cast<CallInst>(I))
2505 if (const Function *F = CI->getCalledFunction()) {
2506 if (F->isDeclaration()) {
2507 switch (F->getNameLen()) {
2508 case 3: // abs(x) != -0.0
2509 if (!strcmp(F->getNameStart(), "abs")) return true;
2510 break;
2511 case 4: // abs[lf](x) != -0.0
2512 if (!strcmp(F->getNameStart(), "absf")) return true;
2513 if (!strcmp(F->getNameStart(), "absl")) return true;
2514 break;
2515 }
2516 }
2517 }
2518 }
2519
2520 return false;
2521}
2522
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002523/// WillNotOverflowSignedAdd - Return true if we can prove that:
2524/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2525/// This basically requires proving that the add in the original type would not
2526/// overflow to change the sign bit or have a carry out.
2527bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528 // There are different heuristics we can use for this. Here are some simple
2529 // ones.
2530
2531 // Add has the property that adding any two 2's complement numbers can only
2532 // have one carry bit which can change a sign. As such, if LHS and RHS each
2533 // have at least two sign bits, we know that the addition of the two values will
2534 // sign extend fine.
2535 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2536 return true;
2537
2538
2539 // If one of the operands only has one non-zero bit, and if the other operand
2540 // has a known-zero bit in a more significant place than it (not including the
2541 // sign bit) the ripple may go up to and fill the zero, but won't change the
2542 // sign. For example, (X & ~4) + 1.
2543
2544 // TODO: Implement.
2545
2546 return false;
2547}
2548
Chris Lattner2454a2e2008-01-29 06:52:45 +00002549
Chris Lattner7e708292002-06-25 16:13:24 +00002550Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002551 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002552 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002553
Chris Lattner66331a42004-04-10 22:01:55 +00002554 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002555 // X + undef -> undef
2556 if (isa<UndefValue>(RHS))
2557 return ReplaceInstUsesWith(I, RHS);
2558
Chris Lattner66331a42004-04-10 22:01:55 +00002559 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002560 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002561 if (RHSC->isNullValue())
2562 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002563 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002564 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2565 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002566 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002567 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002568
Chris Lattner66331a42004-04-10 22:01:55 +00002569 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002570 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002571 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002572 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002573 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002575
2576 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2577 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002578 if (!isa<VectorType>(I.getType())) {
2579 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2580 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2581 KnownZero, KnownOne))
2582 return &I;
2583 }
Chris Lattner66331a42004-04-10 22:01:55 +00002584 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002585
2586 if (isa<PHINode>(LHS))
2587 if (Instruction *NV = FoldOpIntoPhi(I))
2588 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002589
Chris Lattner4f637d42006-01-06 17:59:59 +00002590 ConstantInt *XorRHS = 0;
2591 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002592 if (isa<ConstantInt>(RHSC) &&
2593 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002594 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002595 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002596
Zhou Sheng4351c642007-04-02 08:20:41 +00002597 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002598 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2599 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002600 do {
2601 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002602 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002604 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2605 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002606 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002607 if (!MaskedValueIsZero(XorLHS,
2608 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002609 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002610 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002611 }
2612 }
2613 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002614 C0080Val = APIntOps::lshr(C0080Val, Size);
2615 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2616 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002617
Reid Spencer35c38852007-03-28 01:36:16 +00002618 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002619 // with funny bit widths then this switch statement should be removed. It
2620 // is just here to get the size of the "middle" type back up to something
2621 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002622 const Type *MiddleType = 0;
2623 switch (Size) {
2624 default: break;
2625 case 32: MiddleType = Type::Int32Ty; break;
2626 case 16: MiddleType = Type::Int16Ty; break;
2627 case 8: MiddleType = Type::Int8Ty; break;
2628 }
2629 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002630 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002631 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002632 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002633 }
2634 }
Chris Lattner66331a42004-04-10 22:01:55 +00002635 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002636
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002637 if (I.getType() == Type::Int1Ty)
2638 return BinaryOperator::CreateXor(LHS, RHS);
2639
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002640 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002641 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002642 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002643
2644 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2645 if (RHSI->getOpcode() == Instruction::Sub)
2646 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2647 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2648 }
2649 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2650 if (LHSI->getOpcode() == Instruction::Sub)
2651 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2652 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2653 }
Robert Bocchino71698282004-07-27 21:02:21 +00002654 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002655
Chris Lattner5c4afb92002-05-08 22:46:53 +00002656 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002657 // -A + -B --> -(A + B)
2658 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002659 if (LHS->getType()->isIntOrIntVector()) {
2660 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002661 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002662 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002663 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002664 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002665 }
2666
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002667 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002668 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002669
2670 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002671 if (!isa<Constant>(RHS))
2672 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002673 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002674
Misha Brukmanfd939082005-04-21 23:48:37 +00002675
Chris Lattner50af16a2004-11-13 19:50:12 +00002676 ConstantInt *C2;
2677 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2678 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002679 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002680
2681 // X*C1 + X*C2 --> X * (C1+C2)
2682 ConstantInt *C1;
2683 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002685 }
2686
2687 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002688 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002689 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002690
Chris Lattnere617c9e2007-01-05 02:17:46 +00002691 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002692 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2693 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002694
Chris Lattnerad3448c2003-02-18 19:57:07 +00002695
Chris Lattner564a7272003-08-13 19:01:45 +00002696 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002697 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002698 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2699 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002700
2701 // A+B --> A|B iff A and B have no bits set in common.
2702 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2703 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2704 APInt LHSKnownOne(IT->getBitWidth(), 0);
2705 APInt LHSKnownZero(IT->getBitWidth(), 0);
2706 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2707 if (LHSKnownZero != 0) {
2708 APInt RHSKnownOne(IT->getBitWidth(), 0);
2709 APInt RHSKnownZero(IT->getBitWidth(), 0);
2710 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2711
2712 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002713 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002714 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002715 }
2716 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002717
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002718 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002719 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002720 Value *W, *X, *Y, *Z;
2721 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2722 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2723 if (W != Y) {
2724 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002725 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002726 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002727 std::swap(W, X);
2728 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002729 std::swap(Y, Z);
2730 std::swap(W, X);
2731 }
2732 }
2733
2734 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002735 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002736 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002737 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002738 }
2739 }
2740 }
2741
Chris Lattner6b032052003-10-02 15:11:26 +00002742 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002743 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002744 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002745 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002746
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002747 // (X & FF00) + xx00 -> (X+xx00) & FF00
2748 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002749 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002750 if (Anded == CRHS) {
2751 // See if all bits from the first bit set in the Add RHS up are included
2752 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002753 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002754
2755 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002756 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002757
2758 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002759 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002760
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002761 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2762 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002763 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002764 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002765 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002766 }
2767 }
2768 }
2769
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002770 // Try to fold constant add into select arguments.
2771 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002772 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002773 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002774 }
2775
Reid Spencer1628cec2006-10-26 06:15:43 +00002776 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002777 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002778 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002779 CastInst *CI = dyn_cast<CastInst>(LHS);
2780 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002781 if (!CI) {
2782 CI = dyn_cast<CastInst>(RHS);
2783 Other = LHS;
2784 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002785 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002786 (CI->getType()->getPrimitiveSizeInBits() ==
2787 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002788 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002789 unsigned AS =
2790 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002791 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2792 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002793 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002794 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002795 }
2796 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002797
Chris Lattner42790482007-12-20 01:56:58 +00002798 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002799 {
2800 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2801 Value *Other = RHS;
2802 if (!SI) {
2803 SI = dyn_cast<SelectInst>(RHS);
2804 Other = LHS;
2805 }
Chris Lattner42790482007-12-20 01:56:58 +00002806 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002807 Value *TV = SI->getTrueValue();
2808 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002809 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002810
2811 // Can we fold the add into the argument of the select?
2812 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002813 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2814 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002815 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002816 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2817 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002818 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002819 }
2820 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002821
2822 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2823 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2824 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2825 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002826
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002827 // Check for (add (sext x), y), see if we can merge this into an
2828 // integer add followed by a sext.
2829 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2830 // (add (sext x), cst) --> (sext (add x, cst'))
2831 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2832 Constant *CI =
2833 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2834 if (LHSConv->hasOneUse() &&
2835 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2836 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2837 // Insert the new, smaller add.
2838 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2839 CI, "addconv");
2840 InsertNewInstBefore(NewAdd, I);
2841 return new SExtInst(NewAdd, I.getType());
2842 }
2843 }
2844
2845 // (add (sext x), (sext y)) --> (sext (add int x, y))
2846 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2847 // Only do this if x/y have the same type, if at last one of them has a
2848 // single use (so we don't increase the number of sexts), and if the
2849 // integer add will not overflow.
2850 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2851 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2852 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2853 RHSConv->getOperand(0))) {
2854 // Insert the new integer add.
2855 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2856 RHSConv->getOperand(0),
2857 "addconv");
2858 InsertNewInstBefore(NewAdd, I);
2859 return new SExtInst(NewAdd, I.getType());
2860 }
2861 }
2862 }
2863
2864 // Check for (add double (sitofp x), y), see if we can merge this into an
2865 // integer add followed by a promotion.
2866 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2867 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2868 // ... if the constant fits in the integer value. This is useful for things
2869 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2870 // requires a constant pool load, and generally allows the add to be better
2871 // instcombined.
2872 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2873 Constant *CI =
2874 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2875 if (LHSConv->hasOneUse() &&
2876 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2877 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2878 // Insert the new integer add.
2879 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2880 CI, "addconv");
2881 InsertNewInstBefore(NewAdd, I);
2882 return new SIToFPInst(NewAdd, I.getType());
2883 }
2884 }
2885
2886 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2887 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2888 // Only do this if x/y have the same type, if at last one of them has a
2889 // single use (so we don't increase the number of int->fp conversions),
2890 // and if the integer add will not overflow.
2891 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2892 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2893 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2894 RHSConv->getOperand(0))) {
2895 // Insert the new integer add.
2896 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2897 RHSConv->getOperand(0),
2898 "addconv");
2899 InsertNewInstBefore(NewAdd, I);
2900 return new SIToFPInst(NewAdd, I.getType());
2901 }
2902 }
2903 }
2904
Chris Lattner7e708292002-06-25 16:13:24 +00002905 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002906}
2907
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002908// isSignBit - Return true if the value represented by the constant only has the
2909// highest order bit set.
2910static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002911 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002912 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002913}
2914
Chris Lattner7e708292002-06-25 16:13:24 +00002915Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002916 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002917
Chris Lattner233f7dc2002-08-12 21:17:25 +00002918 if (Op0 == Op1) // sub X, X -> 0
2919 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002920
Chris Lattner233f7dc2002-08-12 21:17:25 +00002921 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002922 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002923 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002924
Chris Lattnere87597f2004-10-16 18:11:37 +00002925 if (isa<UndefValue>(Op0))
2926 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2927 if (isa<UndefValue>(Op1))
2928 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2929
Chris Lattnerd65460f2003-11-05 01:06:05 +00002930 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2931 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002932 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002933 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002934
Chris Lattnerd65460f2003-11-05 01:06:05 +00002935 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002936 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002937 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002938 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002939
Chris Lattner76b7a062007-01-15 07:02:54 +00002940 // -(X >>u 31) -> (X >>s 31)
2941 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002942 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002943 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002944 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002945 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002946 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002947 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002948 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002949 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002950 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002951 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002952 }
2953 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002954 }
2955 else if (SI->getOpcode() == Instruction::AShr) {
2956 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2957 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002958 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002959 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002960 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002961 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002962 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002963 }
2964 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002965 }
2966 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002967 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002968
2969 // Try to fold constant sub into select arguments.
2970 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002971 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002972 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002973
2974 if (isa<PHINode>(Op0))
2975 if (Instruction *NV = FoldOpIntoPhi(I))
2976 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002977 }
2978
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002979 if (I.getType() == Type::Int1Ty)
2980 return BinaryOperator::CreateXor(Op0, Op1);
2981
Chris Lattner43d84d62005-04-07 16:15:25 +00002982 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2983 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002984 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002985 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002986 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002987 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002988 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002989 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2990 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2991 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002992 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002993 Op1I->getOperand(0));
2994 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002995 }
2996
Chris Lattnerfd059242003-10-15 16:48:29 +00002997 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002998 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2999 // is not used by anyone else...
3000 //
Chris Lattner0517e722004-02-02 20:09:56 +00003001 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00003002 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00003003 // Swap the two operands of the subexpr...
3004 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
3005 Op1I->setOperand(0, IIOp1);
3006 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003007
Chris Lattnera2881962003-02-18 19:28:33 +00003008 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003010 }
3011
3012 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3013 //
3014 if (Op1I->getOpcode() == Instruction::And &&
3015 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3016 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3017
Chris Lattnerf523d062004-06-09 05:08:07 +00003018 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003019 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3020 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003021 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003022
Reid Spencerac5209e2006-10-16 23:08:08 +00003023 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003025 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003026 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003027 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003028 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003029 ConstantExpr::getNeg(DivRHS));
3030
Chris Lattnerad3448c2003-02-18 19:57:07 +00003031 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003032 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003033 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003034 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003035 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003036 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003037
3038 // X - ((X / Y) * Y) --> X % Y
3039 if (Op1I->getOpcode() == Instruction::Mul)
3040 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3041 if (Op0 == I->getOperand(0) &&
3042 Op1I->getOperand(1) == I->getOperand(1)) {
3043 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003044 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003045 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003046 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003047 }
Chris Lattner40371712002-05-09 01:29:19 +00003048 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003049 }
Chris Lattnera2881962003-02-18 19:28:33 +00003050
Chris Lattner9919e3d2006-12-02 00:13:08 +00003051 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003052 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003053 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003054 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3055 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3056 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3057 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003058 } else if (Op0I->getOpcode() == Instruction::Sub) {
3059 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003060 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003061 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003062 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003063
Chris Lattner50af16a2004-11-13 19:50:12 +00003064 ConstantInt *C1;
3065 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003066 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003067 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003068
Chris Lattner50af16a2004-11-13 19:50:12 +00003069 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3070 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003071 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003072 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003073 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003074}
3075
Chris Lattnera0141b92007-07-15 20:42:37 +00003076/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3077/// comparison only checks the sign bit. If it only checks the sign bit, set
3078/// TrueIfSigned if the result of the comparison is true when the input value is
3079/// signed.
3080static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3081 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003082 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003083 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3084 TrueIfSigned = true;
3085 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003086 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3087 TrueIfSigned = true;
3088 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003089 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3090 TrueIfSigned = false;
3091 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003092 case ICmpInst::ICMP_UGT:
3093 // True if LHS u> RHS and RHS == high-bit-mask - 1
3094 TrueIfSigned = true;
3095 return RHS->getValue() ==
3096 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3097 case ICmpInst::ICMP_UGE:
3098 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3099 TrueIfSigned = true;
3100 return RHS->getValue() ==
3101 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003102 default:
3103 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003104 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003105}
3106
Chris Lattner7e708292002-06-25 16:13:24 +00003107Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003108 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003109 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003110
Chris Lattnere87597f2004-10-16 18:11:37 +00003111 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3112 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3113
Chris Lattner233f7dc2002-08-12 21:17:25 +00003114 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003115 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3116 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003117
3118 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003119 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003120 if (SI->getOpcode() == Instruction::Shl)
3121 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003122 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003123 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003124
Zhou Sheng843f07672007-04-19 05:39:12 +00003125 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003126 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3127 if (CI->equalsInt(1)) // X * 1 == X
3128 return ReplaceInstUsesWith(I, Op0);
3129 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003130 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003131
Zhou Sheng97b52c22007-03-29 01:57:21 +00003132 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003133 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003134 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003135 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003136 }
Robert Bocchino71698282004-07-27 21:02:21 +00003137 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003138 if (Op1F->isNullValue())
3139 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003140
Chris Lattnera2881962003-02-18 19:28:33 +00003141 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3142 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003143 // We need a better interface for long double here.
3144 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3145 if (Op1F->isExactlyValue(1.0))
3146 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003147 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003148
3149 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3150 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003151 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003152 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003153 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003154 Op1, "tmp");
3155 InsertNewInstBefore(Add, I);
3156 Value *C1C2 = ConstantExpr::getMul(Op1,
3157 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003158 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003159
3160 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003161
3162 // Try to fold constant mul into select arguments.
3163 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003164 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003165 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003166
3167 if (isa<PHINode>(Op0))
3168 if (Instruction *NV = FoldOpIntoPhi(I))
3169 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003170 }
3171
Chris Lattnera4f445b2003-03-10 23:23:04 +00003172 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3173 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003174 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003175
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003176 if (I.getType() == Type::Int1Ty)
3177 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
3178
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003179 // If one of the operands of the multiply is a cast from a boolean value, then
3180 // we know the bool is either zero or one, so this is a 'masking' multiply.
3181 // See if we can simplify things based on how the boolean was originally
3182 // formed.
3183 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003184 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003185 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003186 BoolCast = CI;
3187 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003188 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003189 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003190 BoolCast = CI;
3191 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003192 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003193 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3194 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003195 bool TIS = false;
3196
Reid Spencere4d87aa2006-12-23 06:05:41 +00003197 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003198 // multiply into a shift/and combination.
3199 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003200 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3201 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003202 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003203 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003204 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003205 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003206 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003207 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003208 BoolCast->getOperand(0)->getName()+
3209 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003210
3211 // If the multiply type is not the same as the source type, sign extend
3212 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003213 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003214 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3215 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003216 Instruction::CastOps opcode =
3217 (SrcBits == DstBits ? Instruction::BitCast :
3218 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3219 V = InsertCastBefore(opcode, V, I.getType(), I);
3220 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003221
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003222 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003223 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003224 }
3225 }
3226 }
3227
Chris Lattner7e708292002-06-25 16:13:24 +00003228 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003229}
3230
Reid Spencer1628cec2006-10-26 06:15:43 +00003231/// This function implements the transforms on div instructions that work
3232/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3233/// used by the visitors to those instructions.
3234/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003235Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003236 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003237
Chris Lattner50b2ca42008-02-19 06:12:18 +00003238 // undef / X -> 0 for integer.
3239 // undef / X -> undef for FP (the undef could be a snan).
3240 if (isa<UndefValue>(Op0)) {
3241 if (Op0->getType()->isFPOrFPVector())
3242 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003243 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003244 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003245
3246 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003247 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003248 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003249
Chris Lattner25feae52008-01-28 00:58:18 +00003250 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3251 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003252 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003253 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3254 // the same basic block, then we replace the select with Y, and the
3255 // condition of the select with false (if the cond value is in the same BB).
3256 // If the select has uses other than the div, this allows them to be
3257 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3258 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003259 if (ST->isNullValue()) {
3260 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3261 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003262 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003263 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3264 I.setOperand(1, SI->getOperand(2));
3265 else
3266 UpdateValueUsesWith(SI, SI->getOperand(2));
3267 return &I;
3268 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003269
Chris Lattner25feae52008-01-28 00:58:18 +00003270 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3271 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003272 if (ST->isNullValue()) {
3273 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3274 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003275 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003276 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3277 I.setOperand(1, SI->getOperand(1));
3278 else
3279 UpdateValueUsesWith(SI, SI->getOperand(1));
3280 return &I;
3281 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003282 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003283
Reid Spencer1628cec2006-10-26 06:15:43 +00003284 return 0;
3285}
Misha Brukmanfd939082005-04-21 23:48:37 +00003286
Reid Spencer1628cec2006-10-26 06:15:43 +00003287/// This function implements the transforms common to both integer division
3288/// instructions (udiv and sdiv). It is called by the visitors to those integer
3289/// division instructions.
3290/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003291Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003292 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3293
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003294 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003295 if (Op0 == Op1) {
3296 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3297 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3298 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3299 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3300 }
3301
3302 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3303 return ReplaceInstUsesWith(I, CI);
3304 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003305
Reid Spencer1628cec2006-10-26 06:15:43 +00003306 if (Instruction *Common = commonDivTransforms(I))
3307 return Common;
3308
3309 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3310 // div X, 1 == X
3311 if (RHS->equalsInt(1))
3312 return ReplaceInstUsesWith(I, Op0);
3313
3314 // (X / C1) / C2 -> X / (C1*C2)
3315 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3316 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3317 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003318 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3319 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3320 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003321 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003322 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003323 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003324
Reid Spencerbca0e382007-03-23 20:05:17 +00003325 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003326 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3327 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3328 return R;
3329 if (isa<PHINode>(Op0))
3330 if (Instruction *NV = FoldOpIntoPhi(I))
3331 return NV;
3332 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003333 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003334
Chris Lattnera2881962003-02-18 19:28:33 +00003335 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003336 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003337 if (LHS->equalsInt(0))
3338 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3339
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003340 // It can't be division by zero, hence it must be division by one.
3341 if (I.getType() == Type::Int1Ty)
3342 return ReplaceInstUsesWith(I, Op0);
3343
Reid Spencer1628cec2006-10-26 06:15:43 +00003344 return 0;
3345}
3346
3347Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3349
3350 // Handle the integer div common cases
3351 if (Instruction *Common = commonIDivTransforms(I))
3352 return Common;
3353
3354 // X udiv C^2 -> X >> C
3355 // Check to see if this is an unsigned division with an exact power of 2,
3356 // if so, convert to a right shift.
3357 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003358 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003359 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003360 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003361 }
3362
3363 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003364 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003365 if (RHSI->getOpcode() == Instruction::Shl &&
3366 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003367 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003368 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003369 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003370 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003371 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003372 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003373 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003374 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003375 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003376 }
3377 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003378 }
3379
Reid Spencer1628cec2006-10-26 06:15:43 +00003380 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3381 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003382 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003383 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003384 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003385 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003386 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003387 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003388 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003389 // Construct the "on true" case of the select
3390 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003391 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003392 Op0, TC, SI->getName()+".t");
3393 TSI = InsertNewInstBefore(TSI, I);
3394
3395 // Construct the "on false" case of the select
3396 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003397 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003398 Op0, FC, SI->getName()+".f");
3399 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003400
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003401 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003402 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003403 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003404 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003405 return 0;
3406}
3407
Reid Spencer1628cec2006-10-26 06:15:43 +00003408Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3410
3411 // Handle the integer div common cases
3412 if (Instruction *Common = commonIDivTransforms(I))
3413 return Common;
3414
3415 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3416 // sdiv X, -1 == -X
3417 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003418 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003419
3420 // -X/C -> X/-C
3421 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003422 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003423 }
3424
3425 // If the sign bits of both operands are zero (i.e. we can prove they are
3426 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003427 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003428 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003429 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003430 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003431 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003432 }
3433 }
3434
3435 return 0;
3436}
3437
3438Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3439 return commonDivTransforms(I);
3440}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003441
Reid Spencer0a783f72006-11-02 01:53:59 +00003442/// This function implements the transforms on rem instructions that work
3443/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3444/// is used by the visitors to those instructions.
3445/// @brief Transforms common to all three rem instructions
3446Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003447 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003448
Chris Lattner50b2ca42008-02-19 06:12:18 +00003449 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003450 if (Constant *LHS = dyn_cast<Constant>(Op0))
3451 if (LHS->isNullValue())
3452 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3453
Chris Lattner50b2ca42008-02-19 06:12:18 +00003454 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3455 if (I.getType()->isFPOrFPVector())
3456 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003457 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003458 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003459 if (isa<UndefValue>(Op1))
3460 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003461
3462 // Handle cases involving: rem X, (select Cond, Y, Z)
3463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3464 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3465 // the same basic block, then we replace the select with Y, and the
3466 // condition of the select with false (if the cond value is in the same
3467 // BB). If the select has uses other than the div, this allows them to be
3468 // simplified also.
3469 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3470 if (ST->isNullValue()) {
3471 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3472 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003473 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003474 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3475 I.setOperand(1, SI->getOperand(2));
3476 else
3477 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003478 return &I;
3479 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003480 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3481 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3482 if (ST->isNullValue()) {
3483 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3484 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003485 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003486 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3487 I.setOperand(1, SI->getOperand(1));
3488 else
3489 UpdateValueUsesWith(SI, SI->getOperand(1));
3490 return &I;
3491 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003492 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003493
Reid Spencer0a783f72006-11-02 01:53:59 +00003494 return 0;
3495}
3496
3497/// This function implements the transforms common to both integer remainder
3498/// instructions (urem and srem). It is called by the visitors to those integer
3499/// remainder instructions.
3500/// @brief Common integer remainder transforms
3501Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3503
3504 if (Instruction *common = commonRemTransforms(I))
3505 return common;
3506
Chris Lattner857e8cd2004-12-12 21:48:58 +00003507 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003508 // X % 0 == undef, we don't need to preserve faults!
3509 if (RHS->equalsInt(0))
3510 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3511
Chris Lattnera2881962003-02-18 19:28:33 +00003512 if (RHS->equalsInt(1)) // X % 1 == 0
3513 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3514
Chris Lattner97943922006-02-28 05:49:21 +00003515 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3516 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3517 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3518 return R;
3519 } else if (isa<PHINode>(Op0I)) {
3520 if (Instruction *NV = FoldOpIntoPhi(I))
3521 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003522 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003523
3524 // See if we can fold away this rem instruction.
3525 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3526 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3527 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3528 KnownZero, KnownOne))
3529 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003530 }
Chris Lattnera2881962003-02-18 19:28:33 +00003531 }
3532
Reid Spencer0a783f72006-11-02 01:53:59 +00003533 return 0;
3534}
3535
3536Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3538
3539 if (Instruction *common = commonIRemTransforms(I))
3540 return common;
3541
3542 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3543 // X urem C^2 -> X and C
3544 // Check to see if this is an unsigned remainder with an exact power of 2,
3545 // if so, convert to a bitwise and.
3546 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003547 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003548 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003549 }
3550
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003551 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003552 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3553 if (RHSI->getOpcode() == Instruction::Shl &&
3554 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003555 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003556 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003557 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003558 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003559 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003560 }
3561 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003562 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003563
Reid Spencer0a783f72006-11-02 01:53:59 +00003564 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3565 // where C1&C2 are powers of two.
3566 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3567 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3568 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3569 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003570 if ((STO->getValue().isPowerOf2()) &&
3571 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003572 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003573 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003574 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003575 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003576 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003577 }
3578 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003579 }
3580
Chris Lattner3f5b8772002-05-06 16:14:14 +00003581 return 0;
3582}
3583
Reid Spencer0a783f72006-11-02 01:53:59 +00003584Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3585 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3586
Dan Gohmancff55092007-11-05 23:16:33 +00003587 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003588 if (Instruction *common = commonIRemTransforms(I))
3589 return common;
3590
3591 if (Value *RHSNeg = dyn_castNegVal(Op1))
3592 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003593 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003594 // X % -Y -> X % Y
3595 AddUsesToWorkList(I);
3596 I.setOperand(1, RHSNeg);
3597 return &I;
3598 }
3599
Dan Gohmancff55092007-11-05 23:16:33 +00003600 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003601 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003602 if (I.getType()->isInteger()) {
3603 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3604 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3605 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003606 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003607 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003608 }
3609
3610 return 0;
3611}
3612
3613Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003614 return commonRemTransforms(I);
3615}
3616
Chris Lattner8b170942002-08-09 23:47:40 +00003617// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003618static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003619 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003620 if (!isSigned)
3621 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3622 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003623}
3624
3625// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003626static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003627 if (!isSigned)
3628 return C->getValue() == 1; // unsigned
3629
3630 // Calculate 1111111111000000000000
3631 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3632 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003633}
3634
Chris Lattner457dd822004-06-09 07:59:58 +00003635// isOneBitSet - Return true if there is exactly one bit set in the specified
3636// constant.
3637static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003638 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003639}
3640
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003641// isHighOnes - Return true if the constant is of the form 1+0+.
3642// This is the same as lowones(~X).
3643static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003644 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003645}
3646
Reid Spencere4d87aa2006-12-23 06:05:41 +00003647/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003648/// are carefully arranged to allow folding of expressions such as:
3649///
3650/// (A < B) | (A > B) --> (A != B)
3651///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652/// Note that this is only valid if the first and second predicates have the
3653/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003654///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003655/// Three bits are used to represent the condition, as follows:
3656/// 0 A > B
3657/// 1 A == B
3658/// 2 A < B
3659///
3660/// <=> Value Definition
3661/// 000 0 Always false
3662/// 001 1 A > B
3663/// 010 2 A == B
3664/// 011 3 A >= B
3665/// 100 4 A < B
3666/// 101 5 A != B
3667/// 110 6 A <= B
3668/// 111 7 Always true
3669///
3670static unsigned getICmpCode(const ICmpInst *ICI) {
3671 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003672 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 case ICmpInst::ICMP_UGT: return 1; // 001
3674 case ICmpInst::ICMP_SGT: return 1; // 001
3675 case ICmpInst::ICMP_EQ: return 2; // 010
3676 case ICmpInst::ICMP_UGE: return 3; // 011
3677 case ICmpInst::ICMP_SGE: return 3; // 011
3678 case ICmpInst::ICMP_ULT: return 4; // 100
3679 case ICmpInst::ICMP_SLT: return 4; // 100
3680 case ICmpInst::ICMP_NE: return 5; // 101
3681 case ICmpInst::ICMP_ULE: return 6; // 110
3682 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003683 // True -> 7
3684 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003685 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003686 return 0;
3687 }
3688}
3689
Reid Spencere4d87aa2006-12-23 06:05:41 +00003690/// getICmpValue - This is the complement of getICmpCode, which turns an
3691/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003692/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003693/// of predicate to use in new icmp instructions.
3694static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3695 switch (code) {
3696 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003697 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003698 case 1:
3699 if (sign)
3700 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3701 else
3702 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3703 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3704 case 3:
3705 if (sign)
3706 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3707 else
3708 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3709 case 4:
3710 if (sign)
3711 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3712 else
3713 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3714 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3715 case 6:
3716 if (sign)
3717 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3718 else
3719 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003720 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003721 }
3722}
3723
Reid Spencere4d87aa2006-12-23 06:05:41 +00003724static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3725 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3726 (ICmpInst::isSignedPredicate(p1) &&
3727 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3728 (ICmpInst::isSignedPredicate(p2) &&
3729 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3730}
3731
3732namespace {
3733// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3734struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003735 InstCombiner &IC;
3736 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003737 ICmpInst::Predicate pred;
3738 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3739 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3740 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003741 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003742 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3743 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003744 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3745 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003746 return false;
3747 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748 Instruction *apply(Instruction &Log) const {
3749 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3750 if (ICI->getOperand(0) != LHS) {
3751 assert(ICI->getOperand(1) == LHS);
3752 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003753 }
3754
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003755 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003756 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003757 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003758 unsigned Code;
3759 switch (Log.getOpcode()) {
3760 case Instruction::And: Code = LHSCode & RHSCode; break;
3761 case Instruction::Or: Code = LHSCode | RHSCode; break;
3762 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003763 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003764 }
3765
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003766 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3767 ICmpInst::isSignedPredicate(ICI->getPredicate());
3768
3769 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003770 if (Instruction *I = dyn_cast<Instruction>(RV))
3771 return I;
3772 // Otherwise, it's a constant boolean value...
3773 return IC.ReplaceInstUsesWith(Log, RV);
3774 }
3775};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003776} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003777
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003778// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3779// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003780// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003781Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003782 ConstantInt *OpRHS,
3783 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003784 BinaryOperator &TheAnd) {
3785 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003786 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003787 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003788 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003789
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003790 switch (Op->getOpcode()) {
3791 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003792 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003793 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003794 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003795 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003796 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003797 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003798 }
3799 break;
3800 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003801 if (Together == AndRHS) // (X | C) & C --> C
3802 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003803
Chris Lattner6e7ba452005-01-01 16:22:27 +00003804 if (Op->hasOneUse() && Together != OpRHS) {
3805 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003806 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003807 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003808 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003809 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003810 }
3811 break;
3812 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003813 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003814 // Adding a one to a single bit bit-field should be turned into an XOR
3815 // of the bit. First thing to check is to see if this AND is with a
3816 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003817 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003818
3819 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003820 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003821 // Ok, at this point, we know that we are masking the result of the
3822 // ADD down to exactly one bit. If the constant we are adding has
3823 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003824 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003825
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003826 // Check to see if any bits below the one bit set in AndRHSV are set.
3827 if ((AddRHS & (AndRHSV-1)) == 0) {
3828 // If not, the only thing that can effect the output of the AND is
3829 // the bit specified by AndRHSV. If that bit is set, the effect of
3830 // the XOR is to toggle the bit. If it is clear, then the ADD has
3831 // no effect.
3832 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3833 TheAnd.setOperand(0, X);
3834 return &TheAnd;
3835 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003836 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003837 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003838 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003839 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003840 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003841 }
3842 }
3843 }
3844 }
3845 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003846
3847 case Instruction::Shl: {
3848 // We know that the AND will not produce any of the bits shifted in, so if
3849 // the anded constant includes them, clear them now!
3850 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003851 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003852 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003853 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3854 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003855
Zhou Sheng290bec52007-03-29 08:15:12 +00003856 if (CI->getValue() == ShlMask) {
3857 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003858 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3859 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003860 TheAnd.setOperand(1, CI);
3861 return &TheAnd;
3862 }
3863 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003864 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003865 case Instruction::LShr:
3866 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003867 // We know that the AND will not produce any of the bits shifted in, so if
3868 // the anded constant includes them, clear them now! This only applies to
3869 // unsigned shifts, because a signed shr may bring in set bits!
3870 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003871 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003872 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003873 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3874 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003875
Zhou Sheng290bec52007-03-29 08:15:12 +00003876 if (CI->getValue() == ShrMask) {
3877 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003878 return ReplaceInstUsesWith(TheAnd, Op);
3879 } else if (CI != AndRHS) {
3880 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3881 return &TheAnd;
3882 }
3883 break;
3884 }
3885 case Instruction::AShr:
3886 // Signed shr.
3887 // See if this is shifting in some sign extension, then masking it out
3888 // with an and.
3889 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003890 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003891 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003892 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3893 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003894 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003895 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003896 // Make the argument unsigned.
3897 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003898 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003899 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003900 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003901 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003902 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003903 }
3904 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003905 }
3906 return 0;
3907}
3908
Chris Lattner8b170942002-08-09 23:47:40 +00003909
Chris Lattnera96879a2004-09-29 17:40:11 +00003910/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3911/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003912/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3913/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003914/// insert new instructions.
3915Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003916 bool isSigned, bool Inside,
3917 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003918 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003919 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003920 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003921
Chris Lattnera96879a2004-09-29 17:40:11 +00003922 if (Inside) {
3923 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003924 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003925
Reid Spencere4d87aa2006-12-23 06:05:41 +00003926 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003927 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003928 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003929 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3930 return new ICmpInst(pred, V, Hi);
3931 }
3932
3933 // Emit V-Lo <u Hi-Lo
3934 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003935 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003936 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003937 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3938 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003939 }
3940
3941 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003942 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003943
Reid Spencere4e40032007-03-21 23:19:50 +00003944 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003945 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003946 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003947 ICmpInst::Predicate pred = (isSigned ?
3948 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3949 return new ICmpInst(pred, V, Hi);
3950 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003951
Reid Spencere4e40032007-03-21 23:19:50 +00003952 // Emit V-Lo >u Hi-1-Lo
3953 // Note that Hi has already had one subtracted from it, above.
3954 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003955 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003956 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003957 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3958 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003959}
3960
Chris Lattner7203e152005-09-18 07:22:02 +00003961// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3962// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3963// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3964// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003965static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003966 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003967 uint32_t BitWidth = Val->getType()->getBitWidth();
3968 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003969
3970 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003971 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003972 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003973 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003974 return true;
3975}
3976
Chris Lattner7203e152005-09-18 07:22:02 +00003977/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3978/// where isSub determines whether the operator is a sub. If we can fold one of
3979/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003980///
3981/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3982/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3983/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3984///
3985/// return (A +/- B).
3986///
3987Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003988 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003989 Instruction &I) {
3990 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3991 if (!LHSI || LHSI->getNumOperands() != 2 ||
3992 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3993
3994 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3995
3996 switch (LHSI->getOpcode()) {
3997 default: return 0;
3998 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003999 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004000 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004001 if ((Mask->getValue().countLeadingZeros() +
4002 Mask->getValue().countPopulation()) ==
4003 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004004 break;
4005
4006 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4007 // part, we don't need any explicit masks to take them out of A. If that
4008 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004009 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004010 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004011 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004012 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004013 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004014 break;
4015 }
4016 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004017 return 0;
4018 case Instruction::Or:
4019 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004020 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004021 if ((Mask->getValue().countLeadingZeros() +
4022 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004023 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004024 break;
4025 return 0;
4026 }
4027
4028 Instruction *New;
4029 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004030 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004031 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004032 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004033 return InsertNewInstBefore(New, I);
4034}
4035
Chris Lattner7e708292002-06-25 16:13:24 +00004036Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004037 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004038 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004039
Chris Lattnere87597f2004-10-16 18:11:37 +00004040 if (isa<UndefValue>(Op1)) // X & undef -> 0
4041 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4042
Chris Lattner6e7ba452005-01-01 16:22:27 +00004043 // and X, X = X
4044 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004045 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004046
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004047 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004048 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004049 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004050 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4051 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4052 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004053 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004054 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004055 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004056 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004057 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004058 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004059 } else if (isa<ConstantAggregateZero>(Op1)) {
4060 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004061 }
4062 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004063
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004064 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004065 const APInt& AndRHSMask = AndRHS->getValue();
4066 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004067
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004068 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004069 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004070 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004071 Value *Op0LHS = Op0I->getOperand(0);
4072 Value *Op0RHS = Op0I->getOperand(1);
4073 switch (Op0I->getOpcode()) {
4074 case Instruction::Xor:
4075 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004076 // If the mask is only needed on one incoming arm, push it up.
4077 if (Op0I->hasOneUse()) {
4078 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4079 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004080 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004081 Op0RHS->getName()+".masked");
4082 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004083 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004084 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004085 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004086 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004087 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4088 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004089 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004090 Op0LHS->getName()+".masked");
4091 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004092 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004093 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4094 }
4095 }
4096
Chris Lattner6e7ba452005-01-01 16:22:27 +00004097 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004098 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004099 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4100 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4101 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4102 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004103 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004104 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004105 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004106 break;
4107
4108 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004109 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4110 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4111 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4112 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004113 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004114 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004115 }
4116
Chris Lattner58403262003-07-23 19:25:52 +00004117 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004118 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004119 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004120 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004121 // If this is an integer truncation or change from signed-to-unsigned, and
4122 // if the source is an and/or with immediate, transform it. This
4123 // frequently occurs for bitfield accesses.
4124 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004125 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004126 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004127 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004128 if (CastOp->getOpcode() == Instruction::And) {
4129 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004130 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4131 // This will fold the two constants together, which may allow
4132 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004133 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004134 CastOp->getOperand(0), I.getType(),
4135 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004137 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004138 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004139 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004140 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004141 } else if (CastOp->getOpcode() == Instruction::Or) {
4142 // Change: and (cast (or X, C1) to T), C2
4143 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004144 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004145 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4146 return ReplaceInstUsesWith(I, AndRHS);
4147 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004148 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004149 }
Chris Lattner06782f82003-07-23 19:36:21 +00004150 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004151
4152 // Try to fold constant and into select arguments.
4153 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004154 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004155 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004156 if (isa<PHINode>(Op0))
4157 if (Instruction *NV = FoldOpIntoPhi(I))
4158 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004159 }
4160
Chris Lattner8d969642003-03-10 23:06:50 +00004161 Value *Op0NotVal = dyn_castNotVal(Op0);
4162 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004163
Chris Lattner5b62aa72004-06-18 06:07:51 +00004164 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4165 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4166
Misha Brukmancb6267b2004-07-30 12:50:08 +00004167 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004168 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004169 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004170 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004171 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004172 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004173 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004174
4175 {
Chris Lattner003b6202007-06-15 05:58:24 +00004176 Value *A = 0, *B = 0, *C = 0, *D = 0;
4177 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004178 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4179 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004180
4181 // (A|B) & ~(A&B) -> A^B
4182 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4183 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004184 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004185 }
4186 }
4187
4188 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004189 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4190 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004191
4192 // ~(A&B) & (A|B) -> A^B
4193 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4194 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004195 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004196 }
4197 }
Chris Lattner64daab52006-04-01 08:03:55 +00004198
4199 if (Op0->hasOneUse() &&
4200 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4201 if (A == Op1) { // (A^B)&A -> A&(A^B)
4202 I.swapOperands(); // Simplify below
4203 std::swap(Op0, Op1);
4204 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4205 cast<BinaryOperator>(Op0)->swapOperands();
4206 I.swapOperands(); // Simplify below
4207 std::swap(Op0, Op1);
4208 }
4209 }
4210 if (Op1->hasOneUse() &&
4211 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4212 if (B == Op0) { // B&(A^B) -> B&(B^A)
4213 cast<BinaryOperator>(Op1)->swapOperands();
4214 std::swap(A, B);
4215 }
4216 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004217 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004218 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004219 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004220 }
4221 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004222 }
4223
Reid Spencere4d87aa2006-12-23 06:05:41 +00004224 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4225 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4226 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004227 return R;
4228
Chris Lattner955f3312004-09-28 21:48:02 +00004229 Value *LHSVal, *RHSVal;
4230 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004231 ICmpInst::Predicate LHSCC, RHSCC;
4232 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4233 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4234 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4235 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4236 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4237 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4238 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004239 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4240
4241 // Don't try to fold ICMP_SLT + ICMP_ULT.
4242 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4243 ICmpInst::isSignedPredicate(LHSCC) ==
4244 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004245 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004246 ICmpInst::Predicate GT;
4247 if (ICmpInst::isSignedPredicate(LHSCC) ||
4248 (ICmpInst::isEquality(LHSCC) &&
4249 ICmpInst::isSignedPredicate(RHSCC)))
4250 GT = ICmpInst::ICMP_SGT;
4251 else
4252 GT = ICmpInst::ICMP_UGT;
4253
Reid Spencere4d87aa2006-12-23 06:05:41 +00004254 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4255 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004256 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004257 std::swap(LHS, RHS);
4258 std::swap(LHSCst, RHSCst);
4259 std::swap(LHSCC, RHSCC);
4260 }
4261
Reid Spencere4d87aa2006-12-23 06:05:41 +00004262 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004263 // comparing a value against two constants and and'ing the result
4264 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004265 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4266 // (from the FoldICmpLogical check above), that the two constants
4267 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004268 assert(LHSCst != RHSCst && "Compares not folded above?");
4269
4270 switch (LHSCC) {
4271 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004273 switch (RHSCC) {
4274 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004275 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4276 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4277 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004278 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004279 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4280 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4281 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004282 return ReplaceInstUsesWith(I, LHS);
4283 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004284 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004285 switch (RHSCC) {
4286 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004287 case ICmpInst::ICMP_ULT:
4288 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4289 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4290 break; // (X != 13 & X u< 15) -> no change
4291 case ICmpInst::ICMP_SLT:
4292 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4293 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4294 break; // (X != 13 & X s< 15) -> no change
4295 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4296 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4297 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004298 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004299 case ICmpInst::ICMP_NE:
4300 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004301 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004302 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004303 LHSVal->getName()+".off");
4304 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004305 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4306 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004307 }
4308 break; // (X != 13 & X != 15) -> no change
4309 }
4310 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004311 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004312 switch (RHSCC) {
4313 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004314 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4315 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004316 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004317 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4318 break;
4319 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4320 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004321 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004322 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4323 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004324 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004325 break;
4326 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004327 switch (RHSCC) {
4328 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004329 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4330 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004331 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004332 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4333 break;
4334 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4335 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004336 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004337 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4338 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004339 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004340 break;
4341 case ICmpInst::ICMP_UGT:
4342 switch (RHSCC) {
4343 default: assert(0 && "Unknown integer condition code!");
4344 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4345 return ReplaceInstUsesWith(I, LHS);
4346 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4347 return ReplaceInstUsesWith(I, RHS);
4348 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4349 break;
4350 case ICmpInst::ICMP_NE:
4351 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4352 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4353 break; // (X u> 13 & X != 15) -> no change
4354 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4355 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4356 true, I);
4357 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4358 break;
4359 }
4360 break;
4361 case ICmpInst::ICMP_SGT:
4362 switch (RHSCC) {
4363 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004364 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004365 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4366 return ReplaceInstUsesWith(I, RHS);
4367 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4368 break;
4369 case ICmpInst::ICMP_NE:
4370 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4371 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4372 break; // (X s> 13 & X != 15) -> no change
4373 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4374 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4375 true, I);
4376 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4377 break;
4378 }
4379 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004380 }
4381 }
4382 }
4383
Chris Lattner6fc205f2006-05-05 06:39:07 +00004384 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004385 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4386 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4387 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4388 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004389 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004390 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004391 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4392 I.getType(), TD) &&
4393 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4394 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004395 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004396 Op1C->getOperand(0),
4397 I.getName());
4398 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004399 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004400 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004401 }
Chris Lattnere511b742006-11-14 07:46:50 +00004402
4403 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004404 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4405 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4406 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004407 SI0->getOperand(1) == SI1->getOperand(1) &&
4408 (SI0->hasOneUse() || SI1->hasOneUse())) {
4409 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004410 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004411 SI1->getOperand(0),
4412 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004413 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004414 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004415 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004416 }
4417
Chris Lattner99c65742007-10-24 05:38:08 +00004418 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4419 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4420 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4421 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4422 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4423 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4424 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4425 // If either of the constants are nans, then the whole thing returns
4426 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004427 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004428 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4429 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4430 RHS->getOperand(0));
4431 }
4432 }
4433 }
4434
Chris Lattner7e708292002-06-25 16:13:24 +00004435 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004436}
4437
Chris Lattnerafe91a52006-06-15 19:07:26 +00004438/// CollectBSwapParts - Look to see if the specified value defines a single byte
4439/// in the result. If it does, and if the specified byte hasn't been filled in
4440/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004441static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442 Instruction *I = dyn_cast<Instruction>(V);
4443 if (I == 0) return true;
4444
4445 // If this is an or instruction, it is an inner node of the bswap.
4446 if (I->getOpcode() == Instruction::Or)
4447 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4448 CollectBSwapParts(I->getOperand(1), ByteValues);
4449
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004450 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004451 // If this is a shift by a constant int, and it is "24", then its operand
4452 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004453 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004454 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004455 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004456 8*(ByteValues.size()-1))
4457 return true;
4458
4459 unsigned DestNo;
4460 if (I->getOpcode() == Instruction::Shl) {
4461 // X << 24 defines the top byte with the lowest of the input bytes.
4462 DestNo = ByteValues.size()-1;
4463 } else {
4464 // X >>u 24 defines the low byte with the highest of the input bytes.
4465 DestNo = 0;
4466 }
4467
4468 // If the destination byte value is already defined, the values are or'd
4469 // together, which isn't a bswap (unless it's an or of the same bits).
4470 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4471 return true;
4472 ByteValues[DestNo] = I->getOperand(0);
4473 return false;
4474 }
4475
4476 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4477 // don't have this.
4478 Value *Shift = 0, *ShiftLHS = 0;
4479 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4480 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4481 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4482 return true;
4483 Instruction *SI = cast<Instruction>(Shift);
4484
4485 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004486 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4487 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004488 return true;
4489
4490 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4491 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004492 if (AndAmt->getValue().getActiveBits() > 64)
4493 return true;
4494 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004495 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004496 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004497 break;
4498 // Unknown mask for bswap.
4499 if (DestByte == ByteValues.size()) return true;
4500
Reid Spencerb83eb642006-10-20 07:07:24 +00004501 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004502 unsigned SrcByte;
4503 if (SI->getOpcode() == Instruction::Shl)
4504 SrcByte = DestByte - ShiftBytes;
4505 else
4506 SrcByte = DestByte + ShiftBytes;
4507
4508 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4509 if (SrcByte != ByteValues.size()-DestByte-1)
4510 return true;
4511
4512 // If the destination byte value is already defined, the values are or'd
4513 // together, which isn't a bswap (unless it's an or of the same bits).
4514 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4515 return true;
4516 ByteValues[DestByte] = SI->getOperand(0);
4517 return false;
4518}
4519
4520/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4521/// If so, insert the new bswap intrinsic and return it.
4522Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004523 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4524 if (!ITy || ITy->getBitWidth() % 16)
4525 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004526
4527 /// ByteValues - For each byte of the result, we keep track of which value
4528 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004529 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004530 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004531
4532 // Try to find all the pieces corresponding to the bswap.
4533 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4534 CollectBSwapParts(I.getOperand(1), ByteValues))
4535 return 0;
4536
4537 // Check to see if all of the bytes come from the same value.
4538 Value *V = ByteValues[0];
4539 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4540
4541 // Check to make sure that all of the bytes come from the same value.
4542 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4543 if (ByteValues[i] != V)
4544 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004545 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004546 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004547 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004548 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004549}
4550
4551
Chris Lattner7e708292002-06-25 16:13:24 +00004552Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004553 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004554 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004555
Chris Lattner42593e62007-03-24 23:56:43 +00004556 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004557 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004558
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004559 // or X, X = X
4560 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004561 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004562
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004563 // See if we can simplify any instructions used by the instruction whose sole
4564 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004565 if (!isa<VectorType>(I.getType())) {
4566 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4567 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4568 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4569 KnownZero, KnownOne))
4570 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004571 } else if (isa<ConstantAggregateZero>(Op1)) {
4572 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4573 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4574 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4575 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004576 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004577
4578
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004579
Chris Lattner3f5b8772002-05-06 16:14:14 +00004580 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004581 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004582 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004583 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4584 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004585 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004586 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004587 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004588 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004589 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004590 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004591
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004592 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4593 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004594 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004595 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004596 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004597 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004598 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004599 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004600
4601 // Try to fold constant and into select arguments.
4602 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004603 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004604 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004605 if (isa<PHINode>(Op0))
4606 if (Instruction *NV = FoldOpIntoPhi(I))
4607 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004608 }
4609
Chris Lattner4f637d42006-01-06 17:59:59 +00004610 Value *A = 0, *B = 0;
4611 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004612
4613 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4614 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4615 return ReplaceInstUsesWith(I, Op1);
4616 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4617 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4618 return ReplaceInstUsesWith(I, Op0);
4619
Chris Lattner6423d4c2006-07-10 20:25:24 +00004620 // (A | B) | C and A | (B | C) -> bswap if possible.
4621 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004622 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004623 match(Op1, m_Or(m_Value(), m_Value())) ||
4624 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4625 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004626 if (Instruction *BSwap = MatchBSwap(I))
4627 return BSwap;
4628 }
4629
Chris Lattner6e4c6492005-05-09 04:58:36 +00004630 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4631 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004632 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004633 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004634 InsertNewInstBefore(NOr, I);
4635 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004636 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004637 }
4638
4639 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4640 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004641 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004642 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004643 InsertNewInstBefore(NOr, I);
4644 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004645 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004646 }
4647
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004648 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004649 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004650 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4651 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004652 Value *V1 = 0, *V2 = 0, *V3 = 0;
4653 C1 = dyn_cast<ConstantInt>(C);
4654 C2 = dyn_cast<ConstantInt>(D);
4655 if (C1 && C2) { // (A & C1)|(B & C2)
4656 // If we have: ((V + N) & C1) | (V & C2)
4657 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4658 // replace with V+N.
4659 if (C1->getValue() == ~C2->getValue()) {
4660 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4661 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4662 // Add commutes, try both ways.
4663 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4664 return ReplaceInstUsesWith(I, A);
4665 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4666 return ReplaceInstUsesWith(I, A);
4667 }
4668 // Or commutes, try both ways.
4669 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4670 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4671 // Add commutes, try both ways.
4672 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4673 return ReplaceInstUsesWith(I, B);
4674 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4675 return ReplaceInstUsesWith(I, B);
4676 }
4677 }
Chris Lattner044e5332007-04-08 08:01:49 +00004678 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004679 }
4680
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004681 // Check to see if we have any common things being and'ed. If so, find the
4682 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004683 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4684 if (A == B) // (A & C)|(A & D) == A & (C|D)
4685 V1 = A, V2 = C, V3 = D;
4686 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4687 V1 = A, V2 = B, V3 = C;
4688 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4689 V1 = C, V2 = A, V3 = D;
4690 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4691 V1 = C, V2 = A, V3 = B;
4692
4693 if (V1) {
4694 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004695 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4696 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004697 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004698 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004699 }
Chris Lattnere511b742006-11-14 07:46:50 +00004700
4701 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004702 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4703 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4704 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004705 SI0->getOperand(1) == SI1->getOperand(1) &&
4706 (SI0->hasOneUse() || SI1->hasOneUse())) {
4707 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004708 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004709 SI1->getOperand(0),
4710 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004711 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004712 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004713 }
4714 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004715
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004716 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4717 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004718 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004719 } else {
4720 A = 0;
4721 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004722 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004723 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4724 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004725 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004726
Misha Brukmancb6267b2004-07-30 12:50:08 +00004727 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004728 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004729 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004730 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004731 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004732 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004733 }
Chris Lattnera2881962003-02-18 19:28:33 +00004734
Reid Spencere4d87aa2006-12-23 06:05:41 +00004735 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4736 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4737 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004738 return R;
4739
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004740 Value *LHSVal, *RHSVal;
4741 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004742 ICmpInst::Predicate LHSCC, RHSCC;
4743 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4744 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4745 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4746 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4747 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4748 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4749 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004750 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4751 // We can't fold (ugt x, C) | (sgt x, C2).
4752 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004753 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004754 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004755 bool NeedsSwap;
4756 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004757 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004758 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004759 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004760
4761 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004762 std::swap(LHS, RHS);
4763 std::swap(LHSCst, RHSCst);
4764 std::swap(LHSCC, RHSCC);
4765 }
4766
Reid Spencere4d87aa2006-12-23 06:05:41 +00004767 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004768 // comparing a value against two constants and or'ing the result
4769 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004770 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4771 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004772 // equal.
4773 assert(LHSCst != RHSCst && "Compares not folded above?");
4774
4775 switch (LHSCC) {
4776 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004777 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004778 switch (RHSCC) {
4779 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004780 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004781 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4782 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004783 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004784 LHSVal->getName()+".off");
4785 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004786 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004787 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004788 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004789 break; // (X == 13 | X == 15) -> no change
4790 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4791 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004792 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004793 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4794 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4795 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004796 return ReplaceInstUsesWith(I, RHS);
4797 }
4798 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004799 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004800 switch (RHSCC) {
4801 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004802 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4803 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4804 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004805 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004806 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4807 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4808 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004809 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004810 }
4811 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004812 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004813 switch (RHSCC) {
4814 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004815 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004816 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004817 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004818 // If RHSCst is [us]MAXINT, it is always false. Not handling
4819 // this can cause overflow.
4820 if (RHSCst->isMaxValue(false))
4821 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004822 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4823 false, I);
4824 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4825 break;
4826 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4827 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004828 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004829 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4830 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004831 }
4832 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004833 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004834 switch (RHSCC) {
4835 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004836 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4837 break;
4838 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004839 // If RHSCst is [us]MAXINT, it is always false. Not handling
4840 // this can cause overflow.
4841 if (RHSCst->isMaxValue(true))
4842 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004843 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4844 false, I);
4845 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4846 break;
4847 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4848 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4849 return ReplaceInstUsesWith(I, RHS);
4850 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4851 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004852 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004853 break;
4854 case ICmpInst::ICMP_UGT:
4855 switch (RHSCC) {
4856 default: assert(0 && "Unknown integer condition code!");
4857 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4858 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4859 return ReplaceInstUsesWith(I, LHS);
4860 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4861 break;
4862 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4863 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004864 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004865 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4866 break;
4867 }
4868 break;
4869 case ICmpInst::ICMP_SGT:
4870 switch (RHSCC) {
4871 default: assert(0 && "Unknown integer condition code!");
4872 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4873 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4874 return ReplaceInstUsesWith(I, LHS);
4875 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4876 break;
4877 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4878 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004879 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004880 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4881 break;
4882 }
4883 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004884 }
4885 }
4886 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004887
4888 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004889 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004890 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004891 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004892 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4893 !isa<ICmpInst>(Op1C->getOperand(0))) {
4894 const Type *SrcTy = Op0C->getOperand(0)->getType();
4895 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4896 // Only do this if the casts both really cause code to be
4897 // generated.
4898 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4899 I.getType(), TD) &&
4900 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4901 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004902 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004903 Op1C->getOperand(0),
4904 I.getName());
4905 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004906 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004907 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004908 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004909 }
Chris Lattner99c65742007-10-24 05:38:08 +00004910 }
4911
4912
4913 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4914 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4915 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4916 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004917 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4918 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004919 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4920 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4921 // If either of the constants are nans, then the whole thing returns
4922 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004923 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004924 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4925
4926 // Otherwise, no need to compare the two constants, compare the
4927 // rest.
4928 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4929 RHS->getOperand(0));
4930 }
4931 }
4932 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004933
Chris Lattner7e708292002-06-25 16:13:24 +00004934 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004935}
4936
Dan Gohman844731a2008-05-13 00:00:25 +00004937namespace {
4938
Chris Lattnerc317d392004-02-16 01:20:27 +00004939// XorSelf - Implements: X ^ X --> 0
4940struct XorSelf {
4941 Value *RHS;
4942 XorSelf(Value *rhs) : RHS(rhs) {}
4943 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4944 Instruction *apply(BinaryOperator &Xor) const {
4945 return &Xor;
4946 }
4947};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004948
Dan Gohman844731a2008-05-13 00:00:25 +00004949}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004950
Chris Lattner7e708292002-06-25 16:13:24 +00004951Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004952 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004954
Evan Chengd34af782008-03-25 20:07:13 +00004955 if (isa<UndefValue>(Op1)) {
4956 if (isa<UndefValue>(Op0))
4957 // Handle undef ^ undef -> 0 special case. This is a common
4958 // idiom (misuse).
4959 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004960 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004961 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004962
Chris Lattnerc317d392004-02-16 01:20:27 +00004963 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4964 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004965 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004967 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004968
4969 // See if we can simplify any instructions used by the instruction whose sole
4970 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004971 if (!isa<VectorType>(I.getType())) {
4972 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4973 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4974 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4975 KnownZero, KnownOne))
4976 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004977 } else if (isa<ConstantAggregateZero>(Op1)) {
4978 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004979 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004980
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004981 // Is this a ~ operation?
4982 if (Value *NotOp = dyn_castNotVal(&I)) {
4983 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4984 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4985 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4986 if (Op0I->getOpcode() == Instruction::And ||
4987 Op0I->getOpcode() == Instruction::Or) {
4988 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4989 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4990 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004991 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004992 Op0I->getOperand(1)->getName()+".not");
4993 InsertNewInstBefore(NotY, I);
4994 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004995 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004996 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004997 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004998 }
4999 }
5000 }
5001 }
5002
5003
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005004 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005005 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5006 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5007 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005008 return new ICmpInst(ICI->getInversePredicate(),
5009 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005010
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005011 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5012 return new FCmpInst(FCI->getInversePredicate(),
5013 FCI->getOperand(0), FCI->getOperand(1));
5014 }
5015
Nick Lewycky517e1f52008-05-31 19:01:33 +00005016 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5017 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5018 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5019 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5020 Instruction::CastOps Opcode = Op0C->getOpcode();
5021 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5022 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5023 Op0C->getDestTy())) {
5024 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5025 CI->getOpcode(), CI->getInversePredicate(),
5026 CI->getOperand(0), CI->getOperand(1)), I);
5027 NewCI->takeName(CI);
5028 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5029 }
5030 }
5031 }
5032 }
5033 }
5034
Reid Spencere4d87aa2006-12-23 06:05:41 +00005035 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005036 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005037 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5038 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005039 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5040 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005041 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005042 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005043 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005044
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005046 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005047 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005048 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005049 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005050 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005051 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005052 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005053 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005054 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005055 // (X + C) ^ signbit -> (X + C + signbit)
5056 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005057 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005058
Chris Lattner7c4049c2004-01-12 19:35:11 +00005059 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005060 } else if (Op0I->getOpcode() == Instruction::Or) {
5061 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005062 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005063 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5064 // Anything in both C1 and C2 is known to be zero, remove it from
5065 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005066 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005067 NewRHS = ConstantExpr::getAnd(NewRHS,
5068 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005069 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005070 I.setOperand(0, Op0I->getOperand(0));
5071 I.setOperand(1, NewRHS);
5072 return &I;
5073 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005074 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005075 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005076 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005077
5078 // Try to fold constant and into select arguments.
5079 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005080 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005081 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005082 if (isa<PHINode>(Op0))
5083 if (Instruction *NV = FoldOpIntoPhi(I))
5084 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005085 }
5086
Chris Lattner8d969642003-03-10 23:06:50 +00005087 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005088 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005089 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005090
Chris Lattner8d969642003-03-10 23:06:50 +00005091 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005092 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005093 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005094
Chris Lattner318bf792007-03-18 22:51:34 +00005095
5096 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5097 if (Op1I) {
5098 Value *A, *B;
5099 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5100 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005101 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005102 I.swapOperands();
5103 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005104 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005105 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005106 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005107 }
Chris Lattner318bf792007-03-18 22:51:34 +00005108 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5109 if (Op0 == A) // A^(A^B) == B
5110 return ReplaceInstUsesWith(I, B);
5111 else if (Op0 == B) // A^(B^A) == B
5112 return ReplaceInstUsesWith(I, A);
5113 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005114 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005115 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005116 std::swap(A, B);
5117 }
Chris Lattner318bf792007-03-18 22:51:34 +00005118 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005119 I.swapOperands(); // Simplified below.
5120 std::swap(Op0, Op1);
5121 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005122 }
Chris Lattner318bf792007-03-18 22:51:34 +00005123 }
5124
5125 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5126 if (Op0I) {
5127 Value *A, *B;
5128 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5129 if (A == Op1) // (B|A)^B == (A|B)^B
5130 std::swap(A, B);
5131 if (B == Op1) { // (A|B)^B == A & ~B
5132 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5134 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005135 }
Chris Lattner318bf792007-03-18 22:51:34 +00005136 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5137 if (Op1 == A) // (A^B)^A == B
5138 return ReplaceInstUsesWith(I, B);
5139 else if (Op1 == B) // (B^A)^A == B
5140 return ReplaceInstUsesWith(I, A);
5141 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5142 if (A == Op1) // (A&B)^A -> (B&A)^A
5143 std::swap(A, B);
5144 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005145 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005146 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005147 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5148 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005149 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005150 }
Chris Lattner318bf792007-03-18 22:51:34 +00005151 }
5152
5153 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5154 if (Op0I && Op1I && Op0I->isShift() &&
5155 Op0I->getOpcode() == Op1I->getOpcode() &&
5156 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5157 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5158 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005159 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005160 Op1I->getOperand(0),
5161 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005162 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005163 Op1I->getOperand(1));
5164 }
5165
5166 if (Op0I && Op1I) {
5167 Value *A, *B, *C, *D;
5168 // (A & B)^(A | B) -> A ^ B
5169 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5170 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5171 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005172 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005173 }
5174 // (A | B)^(A & B) -> A ^ B
5175 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5176 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5177 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005178 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005179 }
5180
5181 // (A & B)^(C & D)
5182 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5183 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5184 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5185 // (X & Y)^(X & Y) -> (Y^Z) & X
5186 Value *X = 0, *Y = 0, *Z = 0;
5187 if (A == C)
5188 X = A, Y = B, Z = D;
5189 else if (A == D)
5190 X = A, Y = B, Z = C;
5191 else if (B == C)
5192 X = B, Y = A, Z = D;
5193 else if (B == D)
5194 X = B, Y = A, Z = C;
5195
5196 if (X) {
5197 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005198 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5199 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005200 }
5201 }
5202 }
5203
Reid Spencere4d87aa2006-12-23 06:05:41 +00005204 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5205 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5206 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005207 return R;
5208
Chris Lattner6fc205f2006-05-05 06:39:07 +00005209 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005210 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005211 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005212 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5213 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005214 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005215 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005216 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5217 I.getType(), TD) &&
5218 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5219 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005220 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005221 Op1C->getOperand(0),
5222 I.getName());
5223 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005224 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005225 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005226 }
Chris Lattner99c65742007-10-24 05:38:08 +00005227 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005228
Chris Lattner7e708292002-06-25 16:13:24 +00005229 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005230}
5231
Chris Lattnera96879a2004-09-29 17:40:11 +00005232/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5233/// overflowed for this type.
5234static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005235 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005236 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005237
Reid Spencere4e40032007-03-21 23:19:50 +00005238 if (IsSigned)
5239 if (In2->getValue().isNegative())
5240 return Result->getValue().sgt(In1->getValue());
5241 else
5242 return Result->getValue().slt(In1->getValue());
5243 else
5244 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005245}
5246
Chris Lattner574da9b2005-01-13 20:14:25 +00005247/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5248/// code necessary to compute the offset from the base pointer (without adding
5249/// in the base pointer). Return the result as a signed integer of intptr size.
5250static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5251 TargetData &TD = IC.getTargetData();
5252 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005253 const Type *IntPtrTy = TD.getIntPtrType();
5254 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005255
5256 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005257 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005258 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005259
Chris Lattner574da9b2005-01-13 20:14:25 +00005260 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5261 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005262 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005263 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5264 if (OpC->isZero()) continue;
5265
5266 // Handle a struct index, which adds its field offset to the pointer.
5267 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5268 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5269
5270 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5271 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005272 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005273 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005274 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005275 ConstantInt::get(IntPtrTy, Size),
5276 GEP->getName()+".offs"), I);
5277 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005278 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005279
5280 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5281 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5282 Scale = ConstantExpr::getMul(OC, Scale);
5283 if (Constant *RC = dyn_cast<Constant>(Result))
5284 Result = ConstantExpr::getAdd(RC, Scale);
5285 else {
5286 // Emit an add instruction.
5287 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005288 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005289 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005290 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005291 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005292 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005293 // Convert to correct type.
5294 if (Op->getType() != IntPtrTy) {
5295 if (Constant *OpC = dyn_cast<Constant>(Op))
5296 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5297 else
5298 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5299 Op->getName()+".c"), I);
5300 }
5301 if (Size != 1) {
5302 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5303 if (Constant *OpC = dyn_cast<Constant>(Op))
5304 Op = ConstantExpr::getMul(OpC, Scale);
5305 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005306 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005307 GEP->getName()+".idx"), I);
5308 }
5309
5310 // Emit an add instruction.
5311 if (isa<Constant>(Op) && isa<Constant>(Result))
5312 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5313 cast<Constant>(Result));
5314 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005315 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005316 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005317 }
5318 return Result;
5319}
5320
Chris Lattner10c0d912008-04-22 02:53:33 +00005321
5322/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5323/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5324/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5325/// complex, and scales are involved. The above expression would also be legal
5326/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5327/// later form is less amenable to optimization though, and we are allowed to
5328/// generate the first by knowing that pointer arithmetic doesn't overflow.
5329///
5330/// If we can't emit an optimized form for this expression, this returns null.
5331///
5332static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5333 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005334 TargetData &TD = IC.getTargetData();
5335 gep_type_iterator GTI = gep_type_begin(GEP);
5336
5337 // Check to see if this gep only has a single variable index. If so, and if
5338 // any constant indices are a multiple of its scale, then we can compute this
5339 // in terms of the scale of the variable index. For example, if the GEP
5340 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5341 // because the expression will cross zero at the same point.
5342 unsigned i, e = GEP->getNumOperands();
5343 int64_t Offset = 0;
5344 for (i = 1; i != e; ++i, ++GTI) {
5345 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5346 // Compute the aggregate offset of constant indices.
5347 if (CI->isZero()) continue;
5348
5349 // Handle a struct index, which adds its field offset to the pointer.
5350 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5351 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5352 } else {
5353 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5354 Offset += Size*CI->getSExtValue();
5355 }
5356 } else {
5357 // Found our variable index.
5358 break;
5359 }
5360 }
5361
5362 // If there are no variable indices, we must have a constant offset, just
5363 // evaluate it the general way.
5364 if (i == e) return 0;
5365
5366 Value *VariableIdx = GEP->getOperand(i);
5367 // Determine the scale factor of the variable element. For example, this is
5368 // 4 if the variable index is into an array of i32.
5369 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5370
5371 // Verify that there are no other variable indices. If so, emit the hard way.
5372 for (++i, ++GTI; i != e; ++i, ++GTI) {
5373 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5374 if (!CI) return 0;
5375
5376 // Compute the aggregate offset of constant indices.
5377 if (CI->isZero()) continue;
5378
5379 // Handle a struct index, which adds its field offset to the pointer.
5380 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5381 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5382 } else {
5383 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5384 Offset += Size*CI->getSExtValue();
5385 }
5386 }
5387
5388 // Okay, we know we have a single variable index, which must be a
5389 // pointer/array/vector index. If there is no offset, life is simple, return
5390 // the index.
5391 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5392 if (Offset == 0) {
5393 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5394 // we don't need to bother extending: the extension won't affect where the
5395 // computation crosses zero.
5396 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5397 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5398 VariableIdx->getNameStart(), &I);
5399 return VariableIdx;
5400 }
5401
5402 // Otherwise, there is an index. The computation we will do will be modulo
5403 // the pointer size, so get it.
5404 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5405
5406 Offset &= PtrSizeMask;
5407 VariableScale &= PtrSizeMask;
5408
5409 // To do this transformation, any constant index must be a multiple of the
5410 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5411 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5412 // multiple of the variable scale.
5413 int64_t NewOffs = Offset / (int64_t)VariableScale;
5414 if (Offset != NewOffs*(int64_t)VariableScale)
5415 return 0;
5416
5417 // Okay, we can do this evaluation. Start by converting the index to intptr.
5418 const Type *IntPtrTy = TD.getIntPtrType();
5419 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005420 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005421 true /*SExt*/,
5422 VariableIdx->getNameStart(), &I);
5423 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005424 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005425}
5426
5427
Reid Spencere4d87aa2006-12-23 06:05:41 +00005428/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005429/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005430Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5431 ICmpInst::Predicate Cond,
5432 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005433 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005434
Chris Lattner10c0d912008-04-22 02:53:33 +00005435 // Look through bitcasts.
5436 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5437 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005438
Chris Lattner574da9b2005-01-13 20:14:25 +00005439 Value *PtrBase = GEPLHS->getOperand(0);
5440 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005441 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005442 // This transformation (ignoring the base and scales) is valid because we
5443 // know pointers can't overflow. See if we can output an optimized form.
5444 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5445
5446 // If not, synthesize the offset the hard way.
5447 if (Offset == 0)
5448 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005449 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5450 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005451 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005452 // If the base pointers are different, but the indices are the same, just
5453 // compare the base pointer.
5454 if (PtrBase != GEPRHS->getOperand(0)) {
5455 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005456 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005457 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005458 if (IndicesTheSame)
5459 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5460 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5461 IndicesTheSame = false;
5462 break;
5463 }
5464
5465 // If all indices are the same, just compare the base pointers.
5466 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005467 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5468 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005469
5470 // Otherwise, the base pointers are different and the indices are
5471 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005472 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005473 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005474
Chris Lattnere9d782b2005-01-13 22:25:21 +00005475 // If one of the GEPs has all zero indices, recurse.
5476 bool AllZeros = true;
5477 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5478 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5479 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5480 AllZeros = false;
5481 break;
5482 }
5483 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005484 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5485 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005486
5487 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005488 AllZeros = true;
5489 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5490 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5491 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5492 AllZeros = false;
5493 break;
5494 }
5495 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005496 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005497
Chris Lattner4401c9c2005-01-14 00:20:05 +00005498 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5499 // If the GEPs only differ by one index, compare it.
5500 unsigned NumDifferences = 0; // Keep track of # differences.
5501 unsigned DiffOperand = 0; // The operand that differs.
5502 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5503 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005504 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5505 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005506 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005507 NumDifferences = 2;
5508 break;
5509 } else {
5510 if (NumDifferences++) break;
5511 DiffOperand = i;
5512 }
5513 }
5514
5515 if (NumDifferences == 0) // SAME GEP?
5516 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005517 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005518 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005519
Chris Lattner4401c9c2005-01-14 00:20:05 +00005520 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005521 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5522 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005523 // Make sure we do a signed comparison here.
5524 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005525 }
5526 }
5527
Reid Spencere4d87aa2006-12-23 06:05:41 +00005528 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005529 // the result to fold to a constant!
5530 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5531 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5532 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5533 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5534 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005535 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005536 }
5537 }
5538 return 0;
5539}
5540
Chris Lattnera5406232008-05-19 20:18:56 +00005541/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5542///
5543Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5544 Instruction *LHSI,
5545 Constant *RHSC) {
5546 if (!isa<ConstantFP>(RHSC)) return 0;
5547 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5548
5549 // Get the width of the mantissa. We don't want to hack on conversions that
5550 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005551 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005552 if (MantissaWidth == -1) return 0; // Unknown.
5553
5554 // Check to see that the input is converted from an integer type that is small
5555 // enough that preserves all bits. TODO: check here for "known" sign bits.
5556 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5557 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5558
5559 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5560 if (isa<UIToFPInst>(LHSI))
5561 ++InputSize;
5562
5563 // If the conversion would lose info, don't hack on this.
5564 if ((int)InputSize > MantissaWidth)
5565 return 0;
5566
5567 // Otherwise, we can potentially simplify the comparison. We know that it
5568 // will always come through as an integer value and we know the constant is
5569 // not a NAN (it would have been previously simplified).
5570 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5571
5572 ICmpInst::Predicate Pred;
5573 switch (I.getPredicate()) {
5574 default: assert(0 && "Unexpected predicate!");
5575 case FCmpInst::FCMP_UEQ:
5576 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5577 case FCmpInst::FCMP_UGT:
5578 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5579 case FCmpInst::FCMP_UGE:
5580 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5581 case FCmpInst::FCMP_ULT:
5582 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5583 case FCmpInst::FCMP_ULE:
5584 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5585 case FCmpInst::FCMP_UNE:
5586 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5587 case FCmpInst::FCMP_ORD:
5588 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5589 case FCmpInst::FCMP_UNO:
5590 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5591 }
5592
5593 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5594
5595 // Now we know that the APFloat is a normal number, zero or inf.
5596
Chris Lattner85162782008-05-20 03:50:52 +00005597 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005598 // comparing an i8 to 300.0.
5599 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5600
5601 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5602 // and large values.
5603 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5604 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5605 APFloat::rmNearestTiesToEven);
5606 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005607 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5608 Pred == ICmpInst::ICMP_SLE)
Chris Lattnera5406232008-05-19 20:18:56 +00005609 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5610 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5611 }
5612
5613 // See if the RHS value is < SignedMin.
5614 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5615 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5616 APFloat::rmNearestTiesToEven);
5617 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
Chris Lattner393f7eb2008-05-24 04:06:28 +00005618 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5619 Pred == ICmpInst::ICMP_SGE)
Chris Lattnera5406232008-05-19 20:18:56 +00005620 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5621 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5622 }
5623
5624 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5625 // it may still be fractional. See if it is fractional by casting the FP
5626 // value to the integer value and back, checking for equality. Don't do this
5627 // for zero, because -0.0 is not fractional.
5628 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5629 if (!RHS.isZero() &&
5630 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5631 // If we had a comparison against a fractional value, we have to adjust
5632 // the compare predicate and sometimes the value. RHSC is rounded towards
5633 // zero at this point.
5634 switch (Pred) {
5635 default: assert(0 && "Unexpected integer comparison!");
5636 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5637 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5638 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5639 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5640 case ICmpInst::ICMP_SLE:
5641 // (float)int <= 4.4 --> int <= 4
5642 // (float)int <= -4.4 --> int < -4
5643 if (RHS.isNegative())
5644 Pred = ICmpInst::ICMP_SLT;
5645 break;
5646 case ICmpInst::ICMP_SLT:
5647 // (float)int < -4.4 --> int < -4
5648 // (float)int < 4.4 --> int <= 4
5649 if (!RHS.isNegative())
5650 Pred = ICmpInst::ICMP_SLE;
5651 break;
5652 case ICmpInst::ICMP_SGT:
5653 // (float)int > 4.4 --> int > 4
5654 // (float)int > -4.4 --> int >= -4
5655 if (RHS.isNegative())
5656 Pred = ICmpInst::ICMP_SGE;
5657 break;
5658 case ICmpInst::ICMP_SGE:
5659 // (float)int >= -4.4 --> int >= -4
5660 // (float)int >= 4.4 --> int > 4
5661 if (!RHS.isNegative())
5662 Pred = ICmpInst::ICMP_SGT;
5663 break;
5664 }
5665 }
5666
5667 // Lower this FP comparison into an appropriate integer version of the
5668 // comparison.
5669 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5670}
5671
Reid Spencere4d87aa2006-12-23 06:05:41 +00005672Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5673 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005674 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005675
Chris Lattner58e97462007-01-14 19:42:17 +00005676 // Fold trivial predicates.
5677 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5678 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5679 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5680 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5681
5682 // Simplify 'fcmp pred X, X'
5683 if (Op0 == Op1) {
5684 switch (I.getPredicate()) {
5685 default: assert(0 && "Unknown predicate!");
5686 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5687 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5688 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5689 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5690 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5691 case FCmpInst::FCMP_OLT: // True if ordered and less than
5692 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5693 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5694
5695 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5696 case FCmpInst::FCMP_ULT: // True if unordered or less than
5697 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5698 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5699 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5700 I.setPredicate(FCmpInst::FCMP_UNO);
5701 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5702 return &I;
5703
5704 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5705 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5706 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5707 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5708 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5709 I.setPredicate(FCmpInst::FCMP_ORD);
5710 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5711 return &I;
5712 }
5713 }
5714
Reid Spencere4d87aa2006-12-23 06:05:41 +00005715 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005716 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005717
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 // Handle fcmp with constant RHS
5719 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005720 // If the constant is a nan, see if we can fold the comparison based on it.
5721 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5722 if (CFP->getValueAPF().isNaN()) {
5723 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5724 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005725 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5726 "Comparison must be either ordered or unordered!");
5727 // True if unordered.
5728 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005729 }
5730 }
5731
Reid Spencere4d87aa2006-12-23 06:05:41 +00005732 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5733 switch (LHSI->getOpcode()) {
5734 case Instruction::PHI:
5735 if (Instruction *NV = FoldOpIntoPhi(I))
5736 return NV;
5737 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005738 case Instruction::SIToFP:
5739 case Instruction::UIToFP:
5740 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5741 return NV;
5742 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005743 case Instruction::Select:
5744 // If either operand of the select is a constant, we can fold the
5745 // comparison into the select arms, which will cause one to be
5746 // constant folded and the select turned into a bitwise or.
5747 Value *Op1 = 0, *Op2 = 0;
5748 if (LHSI->hasOneUse()) {
5749 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5750 // Fold the known value into the constant operand.
5751 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5752 // Insert a new FCmp of the other select operand.
5753 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5754 LHSI->getOperand(2), RHSC,
5755 I.getName()), I);
5756 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5757 // Fold the known value into the constant operand.
5758 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5759 // Insert a new FCmp of the other select operand.
5760 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5761 LHSI->getOperand(1), RHSC,
5762 I.getName()), I);
5763 }
5764 }
5765
5766 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005767 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005768 break;
5769 }
5770 }
5771
5772 return Changed ? &I : 0;
5773}
5774
5775Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5776 bool Changed = SimplifyCompare(I);
5777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5778 const Type *Ty = Op0->getType();
5779
5780 // icmp X, X
5781 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005782 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005783 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005784
5785 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005786 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005787
Reid Spencere4d87aa2006-12-23 06:05:41 +00005788 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005789 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005790 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5791 isa<ConstantPointerNull>(Op0)) &&
5792 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005793 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005794 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005795 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005796
Reid Spencere4d87aa2006-12-23 06:05:41 +00005797 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005798 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005799 switch (I.getPredicate()) {
5800 default: assert(0 && "Invalid icmp instruction!");
5801 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005802 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005803 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005804 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005805 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005806 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005807 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005808
Reid Spencere4d87aa2006-12-23 06:05:41 +00005809 case ICmpInst::ICMP_UGT:
5810 case ICmpInst::ICMP_SGT:
5811 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005812 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005813 case ICmpInst::ICMP_ULT:
5814 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005815 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005816 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005817 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005818 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005819 case ICmpInst::ICMP_UGE:
5820 case ICmpInst::ICMP_SGE:
5821 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005822 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005823 case ICmpInst::ICMP_ULE:
5824 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005825 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005826 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005827 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005828 }
5829 }
Chris Lattner8b170942002-08-09 23:47:40 +00005830 }
5831
Chris Lattner2be51ae2004-06-09 04:24:29 +00005832 // See if we are doing a comparison between a constant and an instruction that
5833 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005834 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005835 Value *A, *B;
5836
Chris Lattnerb6566012008-01-05 01:18:20 +00005837 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5838 if (I.isEquality() && CI->isNullValue() &&
5839 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5840 // (icmp cond A B) if cond is equality
5841 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005842 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005843
Reid Spencere4d87aa2006-12-23 06:05:41 +00005844 switch (I.getPredicate()) {
5845 default: break;
5846 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5847 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005848 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005849 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5850 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5851 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5852 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005853 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5854 if (CI->isMinValue(true))
5855 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5856 ConstantInt::getAllOnesValue(Op0->getType()));
5857
Reid Spencere4d87aa2006-12-23 06:05:41 +00005858 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005859
Reid Spencere4d87aa2006-12-23 06:05:41 +00005860 case ICmpInst::ICMP_SLT:
5861 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005862 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005863 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5864 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5865 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5866 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5867 break;
5868
5869 case ICmpInst::ICMP_UGT:
5870 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005871 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005872 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5873 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5874 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5875 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005876
5877 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5878 if (CI->isMaxValue(true))
5879 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5880 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881 break;
5882
5883 case ICmpInst::ICMP_SGT:
5884 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005885 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5887 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5888 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5889 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5890 break;
5891
5892 case ICmpInst::ICMP_ULE:
5893 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005894 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005895 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5896 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5897 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5898 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5899 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005900
Reid Spencere4d87aa2006-12-23 06:05:41 +00005901 case ICmpInst::ICMP_SLE:
5902 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005903 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005904 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5905 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5906 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5907 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5908 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005909
Reid Spencere4d87aa2006-12-23 06:05:41 +00005910 case ICmpInst::ICMP_UGE:
5911 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005912 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005913 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5914 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5915 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5916 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5917 break;
5918
5919 case ICmpInst::ICMP_SGE:
5920 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5923 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5924 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5925 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5926 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005927 }
5928
Reid Spencere4d87aa2006-12-23 06:05:41 +00005929 // If we still have a icmp le or icmp ge instruction, turn it into the
5930 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005931 // already been handled above, this requires little checking.
5932 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005933 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005934 default: break;
5935 case ICmpInst::ICMP_ULE:
5936 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5937 case ICmpInst::ICMP_SLE:
5938 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5939 case ICmpInst::ICMP_UGE:
5940 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5941 case ICmpInst::ICMP_SGE:
5942 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005943 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005944
5945 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005946 // in the input. If this comparison is a normal comparison, it demands all
5947 // bits, if it is a sign bit comparison, it only demands the sign bit.
5948
5949 bool UnusedBit;
5950 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5951
Reid Spencer0460fb32007-03-22 20:36:03 +00005952 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5953 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005954 if (SimplifyDemandedBits(Op0,
5955 isSignBit ? APInt::getSignBit(BitWidth)
5956 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005957 KnownZero, KnownOne, 0))
5958 return &I;
5959
5960 // Given the known and unknown bits, compute a range that the LHS could be
5961 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005962 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005963 // Compute the Min, Max and RHS values based on the known bits. For the
5964 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005965 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5966 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005967 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005968 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5969 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005970 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005971 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5972 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 }
5974 switch (I.getPredicate()) { // LE/GE have been folded already.
5975 default: assert(0 && "Unknown icmp opcode!");
5976 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005977 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005978 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005979 break;
5980 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005981 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005982 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005983 break;
5984 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005985 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005986 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005987 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005988 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005989 break;
5990 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005991 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005992 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005993 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005994 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005995 break;
5996 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005997 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005998 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005999 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006000 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006001 break;
6002 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00006003 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006004 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00006005 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006006 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006007 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006008 }
6009 }
6010
Reid Spencere4d87aa2006-12-23 06:05:41 +00006011 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006012 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006013 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006014 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006015 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6016 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006017 }
6018
Chris Lattner01deb9d2007-04-03 17:43:25 +00006019 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006020 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6021 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6022 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006023 case Instruction::GetElementPtr:
6024 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006025 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006026 bool isAllZeros = true;
6027 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6028 if (!isa<Constant>(LHSI->getOperand(i)) ||
6029 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6030 isAllZeros = false;
6031 break;
6032 }
6033 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006034 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006035 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6036 }
6037 break;
6038
Chris Lattner6970b662005-04-23 15:31:55 +00006039 case Instruction::PHI:
6040 if (Instruction *NV = FoldOpIntoPhi(I))
6041 return NV;
6042 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006043 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006044 // If either operand of the select is a constant, we can fold the
6045 // comparison into the select arms, which will cause one to be
6046 // constant folded and the select turned into a bitwise or.
6047 Value *Op1 = 0, *Op2 = 0;
6048 if (LHSI->hasOneUse()) {
6049 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6050 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006051 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6052 // Insert a new ICmp of the other select operand.
6053 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6054 LHSI->getOperand(2), RHSC,
6055 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006056 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6057 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006058 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6059 // Insert a new ICmp of the other select operand.
6060 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6061 LHSI->getOperand(1), RHSC,
6062 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006063 }
6064 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006065
Chris Lattner6970b662005-04-23 15:31:55 +00006066 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006067 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006068 break;
6069 }
Chris Lattner4802d902007-04-06 18:57:34 +00006070 case Instruction::Malloc:
6071 // If we have (malloc != null), and if the malloc has a single use, we
6072 // can assume it is successful and remove the malloc.
6073 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6074 AddToWorkList(LHSI);
6075 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006076 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006077 }
6078 break;
6079 }
Chris Lattner6970b662005-04-23 15:31:55 +00006080 }
6081
Reid Spencere4d87aa2006-12-23 06:05:41 +00006082 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006083 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006084 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006085 return NI;
6086 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006087 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6088 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006089 return NI;
6090
Reid Spencere4d87aa2006-12-23 06:05:41 +00006091 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006092 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6093 // now.
6094 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6095 if (isa<PointerType>(Op0->getType()) &&
6096 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006097 // We keep moving the cast from the left operand over to the right
6098 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006099 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006100
Chris Lattner57d86372007-01-06 01:45:59 +00006101 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6102 // so eliminate it as well.
6103 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6104 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006105
Chris Lattnerde90b762003-11-03 04:25:02 +00006106 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006107 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006108 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006109 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006110 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006111 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006112 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006113 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006114 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006115 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006116 }
Chris Lattner57d86372007-01-06 01:45:59 +00006117 }
6118
6119 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006120 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006121 // This comes up when you have code like
6122 // int X = A < B;
6123 // if (X) ...
6124 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006125 // with a constant or another cast from the same type.
6126 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006127 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006128 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006129 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006130
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006131 // ~x < ~y --> y < x
6132 { Value *A, *B;
6133 if (match(Op0, m_Not(m_Value(A))) &&
6134 match(Op1, m_Not(m_Value(B))))
6135 return new ICmpInst(I.getPredicate(), B, A);
6136 }
6137
Chris Lattner65b72ba2006-09-18 04:22:48 +00006138 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006139 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006140
6141 // -x == -y --> x == y
6142 if (match(Op0, m_Neg(m_Value(A))) &&
6143 match(Op1, m_Neg(m_Value(B))))
6144 return new ICmpInst(I.getPredicate(), A, B);
6145
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006146 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6147 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6148 Value *OtherVal = A == Op1 ? B : A;
6149 return new ICmpInst(I.getPredicate(), OtherVal,
6150 Constant::getNullValue(A->getType()));
6151 }
6152
6153 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6154 // A^c1 == C^c2 --> A == C^(c1^c2)
6155 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6156 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6157 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006158 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006159 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006160 return new ICmpInst(I.getPredicate(), A,
6161 InsertNewInstBefore(Xor, I));
6162 }
6163
6164 // A^B == A^D -> B == D
6165 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6166 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6167 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6168 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6169 }
6170 }
6171
6172 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6173 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006174 // A == (A^B) -> B == 0
6175 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006176 return new ICmpInst(I.getPredicate(), OtherVal,
6177 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006178 }
6179 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006180 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006181 return new ICmpInst(I.getPredicate(), B,
6182 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006183 }
6184 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006185 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006186 return new ICmpInst(I.getPredicate(), B,
6187 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006188 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006189
Chris Lattner9c2328e2006-11-14 06:06:06 +00006190 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6191 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6192 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6193 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6194 Value *X = 0, *Y = 0, *Z = 0;
6195
6196 if (A == C) {
6197 X = B; Y = D; Z = A;
6198 } else if (A == D) {
6199 X = B; Y = C; Z = A;
6200 } else if (B == C) {
6201 X = A; Y = D; Z = B;
6202 } else if (B == D) {
6203 X = A; Y = C; Z = B;
6204 }
6205
6206 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006207 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6208 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006209 I.setOperand(0, Op1);
6210 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6211 return &I;
6212 }
6213 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006214 }
Chris Lattner7e708292002-06-25 16:13:24 +00006215 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006216}
6217
Chris Lattner562ef782007-06-20 23:46:26 +00006218
6219/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6220/// and CmpRHS are both known to be integer constants.
6221Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6222 ConstantInt *DivRHS) {
6223 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6224 const APInt &CmpRHSV = CmpRHS->getValue();
6225
6226 // FIXME: If the operand types don't match the type of the divide
6227 // then don't attempt this transform. The code below doesn't have the
6228 // logic to deal with a signed divide and an unsigned compare (and
6229 // vice versa). This is because (x /s C1) <s C2 produces different
6230 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6231 // (x /u C1) <u C2. Simply casting the operands and result won't
6232 // work. :( The if statement below tests that condition and bails
6233 // if it finds it.
6234 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6235 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6236 return 0;
6237 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006238 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006239
6240 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6241 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6242 // C2 (CI). By solving for X we can turn this into a range check
6243 // instead of computing a divide.
6244 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6245
6246 // Determine if the product overflows by seeing if the product is
6247 // not equal to the divide. Make sure we do the same kind of divide
6248 // as in the LHS instruction that we're folding.
6249 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6250 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6251
6252 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006253 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006254
Chris Lattner1dbfd482007-06-21 18:11:19 +00006255 // Figure out the interval that is being checked. For example, a comparison
6256 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6257 // Compute this interval based on the constants involved and the signedness of
6258 // the compare/divide. This computes a half-open interval, keeping track of
6259 // whether either value in the interval overflows. After analysis each
6260 // overflow variable is set to 0 if it's corresponding bound variable is valid
6261 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6262 int LoOverflow = 0, HiOverflow = 0;
6263 ConstantInt *LoBound = 0, *HiBound = 0;
6264
6265
Chris Lattner562ef782007-06-20 23:46:26 +00006266 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006267 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006268 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006269 HiOverflow = LoOverflow = ProdOV;
6270 if (!HiOverflow)
6271 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006272 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006273 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006274 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006275 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6276 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006277 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006278 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6279 HiOverflow = LoOverflow = ProdOV;
6280 if (!HiOverflow)
6281 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006282 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006283 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006284 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6285 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006286 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006287 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006288 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006289 }
Dan Gohman76491272008-02-13 22:09:18 +00006290 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006291 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006292 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006293 LoBound = AddOne(DivRHS);
6294 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006295 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6296 HiOverflow = 1; // [INTMIN+1, overflow)
6297 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6298 }
Dan Gohman76491272008-02-13 22:09:18 +00006299 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006300 // e.g. X/-5 op 3 --> [-19, -14)
6301 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006302 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006303 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006304 HiBound = AddOne(Prod);
6305 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006306 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006307 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006308 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006309 HiBound = Subtract(Prod, DivRHS);
6310 }
6311
Chris Lattner1dbfd482007-06-21 18:11:19 +00006312 // Dividing by a negative swaps the condition. LT <-> GT
6313 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006314 }
6315
6316 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006317 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006318 default: assert(0 && "Unhandled icmp opcode!");
6319 case ICmpInst::ICMP_EQ:
6320 if (LoOverflow && HiOverflow)
6321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6322 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006323 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006324 ICmpInst::ICMP_UGE, X, LoBound);
6325 else if (LoOverflow)
6326 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6327 ICmpInst::ICMP_ULT, X, HiBound);
6328 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006329 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006330 case ICmpInst::ICMP_NE:
6331 if (LoOverflow && HiOverflow)
6332 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6333 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006334 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006335 ICmpInst::ICMP_ULT, X, LoBound);
6336 else if (LoOverflow)
6337 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6338 ICmpInst::ICMP_UGE, X, HiBound);
6339 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006340 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006341 case ICmpInst::ICMP_ULT:
6342 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006343 if (LoOverflow == +1) // Low bound is greater than input range.
6344 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6345 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006346 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006347 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006348 case ICmpInst::ICMP_UGT:
6349 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006350 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006351 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006352 else if (HiOverflow == -1) // High bound less than input range.
6353 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6354 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006355 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6356 else
6357 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6358 }
6359}
6360
6361
Chris Lattner01deb9d2007-04-03 17:43:25 +00006362/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6363///
6364Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6365 Instruction *LHSI,
6366 ConstantInt *RHS) {
6367 const APInt &RHSV = RHS->getValue();
6368
6369 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006370 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006371 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6372 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6373 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006374 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6375 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006376 Value *CompareVal = LHSI->getOperand(0);
6377
6378 // If the sign bit of the XorCST is not set, there is no change to
6379 // the operation, just stop using the Xor.
6380 if (!XorCST->getValue().isNegative()) {
6381 ICI.setOperand(0, CompareVal);
6382 AddToWorkList(LHSI);
6383 return &ICI;
6384 }
6385
6386 // Was the old condition true if the operand is positive?
6387 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6388
6389 // If so, the new one isn't.
6390 isTrueIfPositive ^= true;
6391
6392 if (isTrueIfPositive)
6393 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6394 else
6395 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6396 }
6397 }
6398 break;
6399 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6400 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6401 LHSI->getOperand(0)->hasOneUse()) {
6402 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6403
6404 // If the LHS is an AND of a truncating cast, we can widen the
6405 // and/compare to be the input width without changing the value
6406 // produced, eliminating a cast.
6407 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6408 // We can do this transformation if either the AND constant does not
6409 // have its sign bit set or if it is an equality comparison.
6410 // Extending a relational comparison when we're checking the sign
6411 // bit would not work.
6412 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006413 (ICI.isEquality() ||
6414 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006415 uint32_t BitWidth =
6416 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6417 APInt NewCST = AndCST->getValue();
6418 NewCST.zext(BitWidth);
6419 APInt NewCI = RHSV;
6420 NewCI.zext(BitWidth);
6421 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006422 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006423 ConstantInt::get(NewCST),LHSI->getName());
6424 InsertNewInstBefore(NewAnd, ICI);
6425 return new ICmpInst(ICI.getPredicate(), NewAnd,
6426 ConstantInt::get(NewCI));
6427 }
6428 }
6429
6430 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6431 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6432 // happens a LOT in code produced by the C front-end, for bitfield
6433 // access.
6434 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6435 if (Shift && !Shift->isShift())
6436 Shift = 0;
6437
6438 ConstantInt *ShAmt;
6439 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6440 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6441 const Type *AndTy = AndCST->getType(); // Type of the and.
6442
6443 // We can fold this as long as we can't shift unknown bits
6444 // into the mask. This can only happen with signed shift
6445 // rights, as they sign-extend.
6446 if (ShAmt) {
6447 bool CanFold = Shift->isLogicalShift();
6448 if (!CanFold) {
6449 // To test for the bad case of the signed shr, see if any
6450 // of the bits shifted in could be tested after the mask.
6451 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6452 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6453
6454 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6455 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6456 AndCST->getValue()) == 0)
6457 CanFold = true;
6458 }
6459
6460 if (CanFold) {
6461 Constant *NewCst;
6462 if (Shift->getOpcode() == Instruction::Shl)
6463 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6464 else
6465 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6466
6467 // Check to see if we are shifting out any of the bits being
6468 // compared.
6469 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6470 // If we shifted bits out, the fold is not going to work out.
6471 // As a special case, check to see if this means that the
6472 // result is always true or false now.
6473 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6474 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6475 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6476 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6477 } else {
6478 ICI.setOperand(1, NewCst);
6479 Constant *NewAndCST;
6480 if (Shift->getOpcode() == Instruction::Shl)
6481 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6482 else
6483 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6484 LHSI->setOperand(1, NewAndCST);
6485 LHSI->setOperand(0, Shift->getOperand(0));
6486 AddToWorkList(Shift); // Shift is dead.
6487 AddUsesToWorkList(ICI);
6488 return &ICI;
6489 }
6490 }
6491 }
6492
6493 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6494 // preferable because it allows the C<<Y expression to be hoisted out
6495 // of a loop if Y is invariant and X is not.
6496 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6497 ICI.isEquality() && !Shift->isArithmeticShift() &&
6498 isa<Instruction>(Shift->getOperand(0))) {
6499 // Compute C << Y.
6500 Value *NS;
6501 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006502 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006503 Shift->getOperand(1), "tmp");
6504 } else {
6505 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006506 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006507 Shift->getOperand(1), "tmp");
6508 }
6509 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6510
6511 // Compute X & (C << Y).
6512 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006513 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006514 InsertNewInstBefore(NewAnd, ICI);
6515
6516 ICI.setOperand(0, NewAnd);
6517 return &ICI;
6518 }
6519 }
6520 break;
6521
Chris Lattnera0141b92007-07-15 20:42:37 +00006522 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6523 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6524 if (!ShAmt) break;
6525
6526 uint32_t TypeBits = RHSV.getBitWidth();
6527
6528 // Check that the shift amount is in range. If not, don't perform
6529 // undefined shifts. When the shift is visited it will be
6530 // simplified.
6531 if (ShAmt->uge(TypeBits))
6532 break;
6533
6534 if (ICI.isEquality()) {
6535 // If we are comparing against bits always shifted out, the
6536 // comparison cannot succeed.
6537 Constant *Comp =
6538 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6539 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6540 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6541 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6542 return ReplaceInstUsesWith(ICI, Cst);
6543 }
6544
6545 if (LHSI->hasOneUse()) {
6546 // Otherwise strength reduce the shift into an and.
6547 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6548 Constant *Mask =
6549 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006550
Chris Lattnera0141b92007-07-15 20:42:37 +00006551 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006552 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006553 Mask, LHSI->getName()+".mask");
6554 Value *And = InsertNewInstBefore(AndI, ICI);
6555 return new ICmpInst(ICI.getPredicate(), And,
6556 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006557 }
6558 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006559
6560 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6561 bool TrueIfSigned = false;
6562 if (LHSI->hasOneUse() &&
6563 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6564 // (X << 31) <s 0 --> (X&1) != 0
6565 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6566 (TypeBits-ShAmt->getZExtValue()-1));
6567 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006568 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006569 Mask, LHSI->getName()+".mask");
6570 Value *And = InsertNewInstBefore(AndI, ICI);
6571
6572 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6573 And, Constant::getNullValue(And->getType()));
6574 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006575 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006576 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006577
6578 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006579 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006580 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006581 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006582 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006583
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006584 // Check that the shift amount is in range. If not, don't perform
6585 // undefined shifts. When the shift is visited it will be
6586 // simplified.
6587 uint32_t TypeBits = RHSV.getBitWidth();
6588 if (ShAmt->uge(TypeBits))
6589 break;
6590
6591 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006592
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006593 // If we are comparing against bits always shifted out, the
6594 // comparison cannot succeed.
6595 APInt Comp = RHSV << ShAmtVal;
6596 if (LHSI->getOpcode() == Instruction::LShr)
6597 Comp = Comp.lshr(ShAmtVal);
6598 else
6599 Comp = Comp.ashr(ShAmtVal);
6600
6601 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6602 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6603 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6604 return ReplaceInstUsesWith(ICI, Cst);
6605 }
6606
6607 // Otherwise, check to see if the bits shifted out are known to be zero.
6608 // If so, we can compare against the unshifted value:
6609 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006610 if (LHSI->hasOneUse() &&
6611 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006612 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6613 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6614 ConstantExpr::getShl(RHS, ShAmt));
6615 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006616
Evan Chengf30752c2008-04-23 00:38:06 +00006617 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006618 // Otherwise strength reduce the shift into an and.
6619 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6620 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006621
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006622 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006623 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006624 Mask, LHSI->getName()+".mask");
6625 Value *And = InsertNewInstBefore(AndI, ICI);
6626 return new ICmpInst(ICI.getPredicate(), And,
6627 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006628 }
6629 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006630 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006631
6632 case Instruction::SDiv:
6633 case Instruction::UDiv:
6634 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6635 // Fold this div into the comparison, producing a range check.
6636 // Determine, based on the divide type, what the range is being
6637 // checked. If there is an overflow on the low or high side, remember
6638 // it, otherwise compute the range [low, hi) bounding the new value.
6639 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006640 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6641 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6642 DivRHS))
6643 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006644 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006645
6646 case Instruction::Add:
6647 // Fold: icmp pred (add, X, C1), C2
6648
6649 if (!ICI.isEquality()) {
6650 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6651 if (!LHSC) break;
6652 const APInt &LHSV = LHSC->getValue();
6653
6654 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6655 .subtract(LHSV);
6656
6657 if (ICI.isSignedPredicate()) {
6658 if (CR.getLower().isSignBit()) {
6659 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6660 ConstantInt::get(CR.getUpper()));
6661 } else if (CR.getUpper().isSignBit()) {
6662 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6663 ConstantInt::get(CR.getLower()));
6664 }
6665 } else {
6666 if (CR.getLower().isMinValue()) {
6667 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6668 ConstantInt::get(CR.getUpper()));
6669 } else if (CR.getUpper().isMinValue()) {
6670 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6671 ConstantInt::get(CR.getLower()));
6672 }
6673 }
6674 }
6675 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006676 }
6677
6678 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6679 if (ICI.isEquality()) {
6680 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6681
6682 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6683 // the second operand is a constant, simplify a bit.
6684 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6685 switch (BO->getOpcode()) {
6686 case Instruction::SRem:
6687 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6688 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6689 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6690 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6691 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006692 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006693 BO->getName());
6694 InsertNewInstBefore(NewRem, ICI);
6695 return new ICmpInst(ICI.getPredicate(), NewRem,
6696 Constant::getNullValue(BO->getType()));
6697 }
6698 }
6699 break;
6700 case Instruction::Add:
6701 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6702 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6703 if (BO->hasOneUse())
6704 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6705 Subtract(RHS, BOp1C));
6706 } else if (RHSV == 0) {
6707 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6708 // efficiently invertible, or if the add has just this one use.
6709 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6710
6711 if (Value *NegVal = dyn_castNegVal(BOp1))
6712 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6713 else if (Value *NegVal = dyn_castNegVal(BOp0))
6714 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6715 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006716 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006717 InsertNewInstBefore(Neg, ICI);
6718 Neg->takeName(BO);
6719 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6720 }
6721 }
6722 break;
6723 case Instruction::Xor:
6724 // For the xor case, we can xor two constants together, eliminating
6725 // the explicit xor.
6726 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6727 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6728 ConstantExpr::getXor(RHS, BOC));
6729
6730 // FALLTHROUGH
6731 case Instruction::Sub:
6732 // Replace (([sub|xor] A, B) != 0) with (A != B)
6733 if (RHSV == 0)
6734 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6735 BO->getOperand(1));
6736 break;
6737
6738 case Instruction::Or:
6739 // If bits are being or'd in that are not present in the constant we
6740 // are comparing against, then the comparison could never succeed!
6741 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6742 Constant *NotCI = ConstantExpr::getNot(RHS);
6743 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6744 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6745 isICMP_NE));
6746 }
6747 break;
6748
6749 case Instruction::And:
6750 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6751 // If bits are being compared against that are and'd out, then the
6752 // comparison can never succeed!
6753 if ((RHSV & ~BOC->getValue()) != 0)
6754 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6755 isICMP_NE));
6756
6757 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6758 if (RHS == BOC && RHSV.isPowerOf2())
6759 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6760 ICmpInst::ICMP_NE, LHSI,
6761 Constant::getNullValue(RHS->getType()));
6762
6763 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6764 if (isSignBit(BOC)) {
6765 Value *X = BO->getOperand(0);
6766 Constant *Zero = Constant::getNullValue(X->getType());
6767 ICmpInst::Predicate pred = isICMP_NE ?
6768 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6769 return new ICmpInst(pred, X, Zero);
6770 }
6771
6772 // ((X & ~7) == 0) --> X < 8
6773 if (RHSV == 0 && isHighOnes(BOC)) {
6774 Value *X = BO->getOperand(0);
6775 Constant *NegX = ConstantExpr::getNeg(BOC);
6776 ICmpInst::Predicate pred = isICMP_NE ?
6777 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6778 return new ICmpInst(pred, X, NegX);
6779 }
6780 }
6781 default: break;
6782 }
6783 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6784 // Handle icmp {eq|ne} <intrinsic>, intcst.
6785 if (II->getIntrinsicID() == Intrinsic::bswap) {
6786 AddToWorkList(II);
6787 ICI.setOperand(0, II->getOperand(1));
6788 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6789 return &ICI;
6790 }
6791 }
6792 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006793 // If the LHS is a cast from an integral value of the same size,
6794 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006795 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6796 Value *CastOp = Cast->getOperand(0);
6797 const Type *SrcTy = CastOp->getType();
6798 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6799 if (SrcTy->isInteger() &&
6800 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6801 // If this is an unsigned comparison, try to make the comparison use
6802 // smaller constant values.
6803 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6804 // X u< 128 => X s> -1
6805 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6806 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6807 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6808 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6809 // X u> 127 => X s< 0
6810 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6811 Constant::getNullValue(SrcTy));
6812 }
6813 }
6814 }
6815 }
6816 return 0;
6817}
6818
6819/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6820/// We only handle extending casts so far.
6821///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006822Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6823 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006824 Value *LHSCIOp = LHSCI->getOperand(0);
6825 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006826 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006827 Value *RHSCIOp;
6828
Chris Lattner8c756c12007-05-05 22:41:33 +00006829 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6830 // integer type is the same size as the pointer type.
6831 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6832 getTargetData().getPointerSizeInBits() ==
6833 cast<IntegerType>(DestTy)->getBitWidth()) {
6834 Value *RHSOp = 0;
6835 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006836 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006837 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6838 RHSOp = RHSC->getOperand(0);
6839 // If the pointer types don't match, insert a bitcast.
6840 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006841 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006842 }
6843
6844 if (RHSOp)
6845 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6846 }
6847
6848 // The code below only handles extension cast instructions, so far.
6849 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006850 if (LHSCI->getOpcode() != Instruction::ZExt &&
6851 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006852 return 0;
6853
Reid Spencere4d87aa2006-12-23 06:05:41 +00006854 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6855 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006856
Reid Spencere4d87aa2006-12-23 06:05:41 +00006857 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006858 // Not an extension from the same type?
6859 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006860 if (RHSCIOp->getType() != LHSCIOp->getType())
6861 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006862
Nick Lewycky4189a532008-01-28 03:48:02 +00006863 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006864 // and the other is a zext), then we can't handle this.
6865 if (CI->getOpcode() != LHSCI->getOpcode())
6866 return 0;
6867
Nick Lewycky4189a532008-01-28 03:48:02 +00006868 // Deal with equality cases early.
6869 if (ICI.isEquality())
6870 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6871
6872 // A signed comparison of sign extended values simplifies into a
6873 // signed comparison.
6874 if (isSignedCmp && isSignedExt)
6875 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6876
6877 // The other three cases all fold into an unsigned comparison.
6878 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006879 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006880
Reid Spencere4d87aa2006-12-23 06:05:41 +00006881 // If we aren't dealing with a constant on the RHS, exit early
6882 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6883 if (!CI)
6884 return 0;
6885
6886 // Compute the constant that would happen if we truncated to SrcTy then
6887 // reextended to DestTy.
6888 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6889 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6890
6891 // If the re-extended constant didn't change...
6892 if (Res2 == CI) {
6893 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6894 // For example, we might have:
6895 // %A = sext short %X to uint
6896 // %B = icmp ugt uint %A, 1330
6897 // It is incorrect to transform this into
6898 // %B = icmp ugt short %X, 1330
6899 // because %A may have negative value.
6900 //
6901 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6902 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006903 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006904 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6905 else
6906 return 0;
6907 }
6908
6909 // The re-extended constant changed so the constant cannot be represented
6910 // in the shorter type. Consequently, we cannot emit a simple comparison.
6911
6912 // First, handle some easy cases. We know the result cannot be equal at this
6913 // point so handle the ICI.isEquality() cases
6914 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006915 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006916 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006917 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006918
6919 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6920 // should have been folded away previously and not enter in here.
6921 Value *Result;
6922 if (isSignedCmp) {
6923 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006924 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006925 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006926 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006927 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006928 } else {
6929 // We're performing an unsigned comparison.
6930 if (isSignedExt) {
6931 // We're performing an unsigned comp with a sign extended value.
6932 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006933 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006934 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6935 NegOne, ICI.getName()), ICI);
6936 } else {
6937 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006938 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006939 }
6940 }
6941
6942 // Finally, return the value computed.
6943 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6944 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6945 return ReplaceInstUsesWith(ICI, Result);
6946 } else {
6947 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6948 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6949 "ICmp should be folded!");
6950 if (Constant *CI = dyn_cast<Constant>(Result))
6951 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6952 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006953 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006954 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006955}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006956
Reid Spencer832254e2007-02-02 02:16:23 +00006957Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6958 return commonShiftTransforms(I);
6959}
6960
6961Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6962 return commonShiftTransforms(I);
6963}
6964
6965Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006966 if (Instruction *R = commonShiftTransforms(I))
6967 return R;
6968
6969 Value *Op0 = I.getOperand(0);
6970
6971 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6972 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6973 if (CSI->isAllOnesValue())
6974 return ReplaceInstUsesWith(I, CSI);
6975
6976 // See if we can turn a signed shr into an unsigned shr.
6977 if (MaskedValueIsZero(Op0,
6978 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006979 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006980
6981 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006982}
6983
6984Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6985 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006986 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006987
6988 // shl X, 0 == X and shr X, 0 == X
6989 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006990 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006991 Op0 == Constant::getNullValue(Op0->getType()))
6992 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006993
Reid Spencere4d87aa2006-12-23 06:05:41 +00006994 if (isa<UndefValue>(Op0)) {
6995 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006996 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006997 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006998 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6999 }
7000 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007001 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7002 return ReplaceInstUsesWith(I, Op0);
7003 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00007004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007005 }
7006
Chris Lattner2eefe512004-04-09 19:05:30 +00007007 // Try to fold constant and into select arguments.
7008 if (isa<Constant>(Op0))
7009 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007010 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007011 return R;
7012
Reid Spencerb83eb642006-10-20 07:07:24 +00007013 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007014 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7015 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007016 return 0;
7017}
7018
Reid Spencerb83eb642006-10-20 07:07:24 +00007019Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007020 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007021 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007022
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007023 // See if we can simplify any instructions used by the instruction whose sole
7024 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007025 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7026 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
7027 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007028 KnownZero, KnownOne))
7029 return &I;
7030
Chris Lattner4d5542c2006-01-06 07:12:35 +00007031 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7032 // of a signed value.
7033 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007034 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007035 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007036 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7037 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007038 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007039 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007040 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007041 }
7042
7043 // ((X*C1) << C2) == (X * (C1 << C2))
7044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7045 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7046 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007047 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007048 ConstantExpr::getShl(BOOp, Op1));
7049
7050 // Try to fold constant and into select arguments.
7051 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7052 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7053 return R;
7054 if (isa<PHINode>(Op0))
7055 if (Instruction *NV = FoldOpIntoPhi(I))
7056 return NV;
7057
Chris Lattner8999dd32007-12-22 09:07:47 +00007058 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7059 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7060 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7061 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7062 // place. Don't try to do this transformation in this case. Also, we
7063 // require that the input operand is a shift-by-constant so that we have
7064 // confidence that the shifts will get folded together. We could do this
7065 // xform in more cases, but it is unlikely to be profitable.
7066 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7067 isa<ConstantInt>(TrOp->getOperand(1))) {
7068 // Okay, we'll do this xform. Make the shift of shift.
7069 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007070 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007071 I.getName());
7072 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7073
7074 // For logical shifts, the truncation has the effect of making the high
7075 // part of the register be zeros. Emulate this by inserting an AND to
7076 // clear the top bits as needed. This 'and' will usually be zapped by
7077 // other xforms later if dead.
7078 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7079 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7080 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7081
7082 // The mask we constructed says what the trunc would do if occurring
7083 // between the shifts. We want to know the effect *after* the second
7084 // shift. We know that it is a logical shift by a constant, so adjust the
7085 // mask as appropriate.
7086 if (I.getOpcode() == Instruction::Shl)
7087 MaskV <<= Op1->getZExtValue();
7088 else {
7089 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7090 MaskV = MaskV.lshr(Op1->getZExtValue());
7091 }
7092
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007093 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007094 TI->getName());
7095 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7096
7097 // Return the value truncated to the interesting size.
7098 return new TruncInst(And, I.getType());
7099 }
7100 }
7101
Chris Lattner4d5542c2006-01-06 07:12:35 +00007102 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007103 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7104 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7105 Value *V1, *V2;
7106 ConstantInt *CC;
7107 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007108 default: break;
7109 case Instruction::Add:
7110 case Instruction::And:
7111 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007112 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007113 // These operators commute.
7114 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007115 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7116 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007117 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007118 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007119 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007120 Op0BO->getName());
7121 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007122 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007123 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007124 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007125 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007126 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007127 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007128 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007129 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007130
Chris Lattner150f12a2005-09-18 06:30:59 +00007131 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007132 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007133 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007134 match(Op0BOOp1,
7135 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007136 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7137 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007138 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007139 Op0BO->getOperand(0), Op1,
7140 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007141 InsertNewInstBefore(YS, I); // (Y << C)
7142 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007143 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007144 V1->getName()+".mask");
7145 InsertNewInstBefore(XM, I); // X & (CC << C)
7146
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007147 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007148 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007149 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007150
Reid Spencera07cb7d2007-02-02 14:41:37 +00007151 // FALL THROUGH.
7152 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007153 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007154 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7155 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007156 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007157 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007158 Op0BO->getOperand(1), Op1,
7159 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007160 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007161 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007162 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007163 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007164 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007165 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007166 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007167 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007168 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007169
Chris Lattner13d4ab42006-05-31 21:14:00 +00007170 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007171 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7172 match(Op0BO->getOperand(0),
7173 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007174 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007175 cast<BinaryOperator>(Op0BO->getOperand(0))
7176 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007177 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007178 Op0BO->getOperand(1), Op1,
7179 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007180 InsertNewInstBefore(YS, I); // (Y << C)
7181 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007182 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007183 V1->getName()+".mask");
7184 InsertNewInstBefore(XM, I); // X & (CC << C)
7185
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007186 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007187 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007188
Chris Lattner11021cb2005-09-18 05:12:10 +00007189 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007190 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007191 }
7192
7193
7194 // If the operand is an bitwise operator with a constant RHS, and the
7195 // shift is the only use, we can pull it out of the shift.
7196 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7197 bool isValid = true; // Valid only for And, Or, Xor
7198 bool highBitSet = false; // Transform if high bit of constant set?
7199
7200 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007201 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007202 case Instruction::Add:
7203 isValid = isLeftShift;
7204 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007205 case Instruction::Or:
7206 case Instruction::Xor:
7207 highBitSet = false;
7208 break;
7209 case Instruction::And:
7210 highBitSet = true;
7211 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007212 }
7213
7214 // If this is a signed shift right, and the high bit is modified
7215 // by the logical operation, do not perform the transformation.
7216 // The highBitSet boolean indicates the value of the high bit of
7217 // the constant which would cause it to be modified for this
7218 // operation.
7219 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007220 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007221 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007222
7223 if (isValid) {
7224 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7225
7226 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007227 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007228 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007229 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007230
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007231 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007232 NewRHS);
7233 }
7234 }
7235 }
7236 }
7237
Chris Lattnerad0124c2006-01-06 07:52:12 +00007238 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007239 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7240 if (ShiftOp && !ShiftOp->isShift())
7241 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007242
Reid Spencerb83eb642006-10-20 07:07:24 +00007243 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007244 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007245 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7246 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007247 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7248 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7249 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007250
Zhou Sheng4351c642007-04-02 08:20:41 +00007251 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007252 if (AmtSum > TypeBits)
7253 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007254
7255 const IntegerType *Ty = cast<IntegerType>(I.getType());
7256
7257 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007258 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007259 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007260 ConstantInt::get(Ty, AmtSum));
7261 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7262 I.getOpcode() == Instruction::AShr) {
7263 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007264 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007265 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7266 I.getOpcode() == Instruction::LShr) {
7267 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7268 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007269 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007270 InsertNewInstBefore(Shift, I);
7271
Zhou Shenge9e03f62007-03-28 15:02:20 +00007272 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007273 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007274 }
7275
Chris Lattnerb87056f2007-02-05 00:57:54 +00007276 // Okay, if we get here, one shift must be left, and the other shift must be
7277 // right. See if the amounts are equal.
7278 if (ShiftAmt1 == ShiftAmt2) {
7279 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7280 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007281 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007282 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007283 }
7284 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7285 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007286 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007287 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007288 }
7289 // We can simplify ((X << C) >>s C) into a trunc + sext.
7290 // NOTE: we could do this for any C, but that would make 'unusual' integer
7291 // types. For now, just stick to ones well-supported by the code
7292 // generators.
7293 const Type *SExtType = 0;
7294 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007295 case 1 :
7296 case 8 :
7297 case 16 :
7298 case 32 :
7299 case 64 :
7300 case 128:
7301 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7302 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007303 default: break;
7304 }
7305 if (SExtType) {
7306 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7307 InsertNewInstBefore(NewTrunc, I);
7308 return new SExtInst(NewTrunc, Ty);
7309 }
7310 // Otherwise, we can't handle it yet.
7311 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007312 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007313
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007314 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007315 if (I.getOpcode() == Instruction::Shl) {
7316 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7317 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007318 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007319 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007320 InsertNewInstBefore(Shift, I);
7321
Reid Spencer55702aa2007-03-25 21:11:44 +00007322 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007323 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007324 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007325
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007326 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007327 if (I.getOpcode() == Instruction::LShr) {
7328 assert(ShiftOp->getOpcode() == Instruction::Shl);
7329 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007330 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007331 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007332
Reid Spencerd5e30f02007-03-26 17:18:58 +00007333 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007334 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007335 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007336
7337 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7338 } else {
7339 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007340 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007341
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007342 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007343 if (I.getOpcode() == Instruction::Shl) {
7344 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7345 ShiftOp->getOpcode() == Instruction::AShr);
7346 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007347 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007348 ConstantInt::get(Ty, ShiftDiff));
7349 InsertNewInstBefore(Shift, I);
7350
Reid Spencer55702aa2007-03-25 21:11:44 +00007351 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007352 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007353 }
7354
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007355 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007356 if (I.getOpcode() == Instruction::LShr) {
7357 assert(ShiftOp->getOpcode() == Instruction::Shl);
7358 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007359 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007360 InsertNewInstBefore(Shift, I);
7361
Reid Spencer68d27cf2007-03-26 23:45:51 +00007362 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007363 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007364 }
7365
7366 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007367 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007368 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007369 return 0;
7370}
7371
Chris Lattnera1be5662002-05-02 17:06:02 +00007372
Chris Lattnercfd65102005-10-29 04:36:15 +00007373/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7374/// expression. If so, decompose it, returning some value X, such that Val is
7375/// X*Scale+Offset.
7376///
7377static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007378 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007379 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007380 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007381 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007382 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007383 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007384 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7385 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7386 if (I->getOpcode() == Instruction::Shl) {
7387 // This is a value scaled by '1 << the shift amt'.
7388 Scale = 1U << RHS->getZExtValue();
7389 Offset = 0;
7390 return I->getOperand(0);
7391 } else if (I->getOpcode() == Instruction::Mul) {
7392 // This value is scaled by 'RHS'.
7393 Scale = RHS->getZExtValue();
7394 Offset = 0;
7395 return I->getOperand(0);
7396 } else if (I->getOpcode() == Instruction::Add) {
7397 // We have X+C. Check to see if we really have (X*C2)+C1,
7398 // where C1 is divisible by C2.
7399 unsigned SubScale;
7400 Value *SubVal =
7401 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7402 Offset += RHS->getZExtValue();
7403 Scale = SubScale;
7404 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007405 }
7406 }
7407 }
7408
7409 // Otherwise, we can't look past this.
7410 Scale = 1;
7411 Offset = 0;
7412 return Val;
7413}
7414
7415
Chris Lattnerb3f83972005-10-24 06:03:58 +00007416/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7417/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007418Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007419 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007420 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007421
Chris Lattnerb53c2382005-10-24 06:22:12 +00007422 // Remove any uses of AI that are dead.
7423 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007424
Chris Lattnerb53c2382005-10-24 06:22:12 +00007425 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7426 Instruction *User = cast<Instruction>(*UI++);
7427 if (isInstructionTriviallyDead(User)) {
7428 while (UI != E && *UI == User)
7429 ++UI; // If this instruction uses AI more than once, don't break UI.
7430
Chris Lattnerb53c2382005-10-24 06:22:12 +00007431 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007432 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007433 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007434 }
7435 }
7436
Chris Lattnerb3f83972005-10-24 06:03:58 +00007437 // Get the type really allocated and the type casted to.
7438 const Type *AllocElTy = AI.getAllocatedType();
7439 const Type *CastElTy = PTy->getElementType();
7440 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007441
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007442 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7443 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007444 if (CastElTyAlign < AllocElTyAlign) return 0;
7445
Chris Lattner39387a52005-10-24 06:35:18 +00007446 // If the allocation has multiple uses, only promote it if we are strictly
7447 // increasing the alignment of the resultant allocation. If we keep it the
7448 // same, we open the door to infinite loops of various kinds.
7449 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7450
Duncan Sands514ab342007-11-01 20:53:16 +00007451 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7452 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007453 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007454
Chris Lattner455fcc82005-10-29 03:19:53 +00007455 // See if we can satisfy the modulus by pulling a scale out of the array
7456 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007457 unsigned ArraySizeScale;
7458 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007459 Value *NumElements = // See if the array size is a decomposable linear expr.
7460 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7461
Chris Lattner455fcc82005-10-29 03:19:53 +00007462 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7463 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007464 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7465 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007466
Chris Lattner455fcc82005-10-29 03:19:53 +00007467 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7468 Value *Amt = 0;
7469 if (Scale == 1) {
7470 Amt = NumElements;
7471 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007472 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007473 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7474 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007475 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007476 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007477 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007478 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007479 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007480 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007481 }
7482
Jeff Cohen86796be2007-04-04 16:58:57 +00007483 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7484 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007485 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007486 Amt = InsertNewInstBefore(Tmp, AI);
7487 }
7488
Chris Lattnerb3f83972005-10-24 06:03:58 +00007489 AllocationInst *New;
7490 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007491 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007492 else
Chris Lattner6934a042007-02-11 01:23:03 +00007493 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007494 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007495 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007496
7497 // If the allocation has multiple uses, insert a cast and change all things
7498 // that used it to use the new cast. This will also hack on CI, but it will
7499 // die soon.
7500 if (!AI.hasOneUse()) {
7501 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007502 // New is the allocation instruction, pointer typed. AI is the original
7503 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7504 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007505 InsertNewInstBefore(NewCast, AI);
7506 AI.replaceAllUsesWith(NewCast);
7507 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007508 return ReplaceInstUsesWith(CI, New);
7509}
7510
Chris Lattner70074e02006-05-13 02:06:03 +00007511/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007512/// and return it as type Ty without inserting any new casts and without
7513/// changing the computed value. This is used by code that tries to decide
7514/// whether promoting or shrinking integer operations to wider or smaller types
7515/// will allow us to eliminate a truncate or extend.
7516///
7517/// This is a truncation operation if Ty is smaller than V->getType(), or an
7518/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007519bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7520 unsigned CastOpc,
7521 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007522 // We can always evaluate constants in another type.
7523 if (isa<ConstantInt>(V))
7524 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007525
7526 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007527 if (!I) return false;
7528
7529 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007530
Chris Lattner951626b2007-08-02 06:11:14 +00007531 // If this is an extension or truncate, we can often eliminate it.
7532 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7533 // If this is a cast from the destination type, we can trivially eliminate
7534 // it, and this will remove a cast overall.
7535 if (I->getOperand(0)->getType() == Ty) {
7536 // If the first operand is itself a cast, and is eliminable, do not count
7537 // this as an eliminable cast. We would prefer to eliminate those two
7538 // casts first.
7539 if (!isa<CastInst>(I->getOperand(0)))
7540 ++NumCastsRemoved;
7541 return true;
7542 }
7543 }
7544
7545 // We can't extend or shrink something that has multiple uses: doing so would
7546 // require duplicating the instruction in general, which isn't profitable.
7547 if (!I->hasOneUse()) return false;
7548
Chris Lattner70074e02006-05-13 02:06:03 +00007549 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007550 case Instruction::Add:
7551 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007552 case Instruction::And:
7553 case Instruction::Or:
7554 case Instruction::Xor:
7555 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007556 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7557 NumCastsRemoved) &&
7558 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7559 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007560
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007561 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007562 // A multiply can be truncated by truncating its operands.
7563 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7564 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7565 NumCastsRemoved) &&
7566 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7567 NumCastsRemoved);
7568
Chris Lattner46b96052006-11-29 07:18:39 +00007569 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007570 // If we are truncating the result of this SHL, and if it's a shift of a
7571 // constant amount, we can always perform a SHL in a smaller type.
7572 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007573 uint32_t BitWidth = Ty->getBitWidth();
7574 if (BitWidth < OrigTy->getBitWidth() &&
7575 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007576 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7577 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007578 }
7579 break;
7580 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007581 // If this is a truncate of a logical shr, we can truncate it to a smaller
7582 // lshr iff we know that the bits we would otherwise be shifting in are
7583 // already zeros.
7584 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007585 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7586 uint32_t BitWidth = Ty->getBitWidth();
7587 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007588 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007589 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7590 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007591 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7592 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007593 }
7594 }
Chris Lattner46b96052006-11-29 07:18:39 +00007595 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007596 case Instruction::ZExt:
7597 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007598 case Instruction::Trunc:
7599 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007600 // can safely replace it. Note that replacing it does not reduce the number
7601 // of casts in the input.
7602 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007603 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007604
Reid Spencer3da59db2006-11-27 01:05:10 +00007605 break;
7606 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007607 // TODO: Can handle more cases here.
7608 break;
7609 }
7610
7611 return false;
7612}
7613
7614/// EvaluateInDifferentType - Given an expression that
7615/// CanEvaluateInDifferentType returns true for, actually insert the code to
7616/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007617Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007618 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007619 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007620 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007621
7622 // Otherwise, it must be an instruction.
7623 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007624 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007625 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007626 case Instruction::Add:
7627 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007628 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007629 case Instruction::And:
7630 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007631 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007632 case Instruction::AShr:
7633 case Instruction::LShr:
7634 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007635 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007636 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007637 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007638 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007639 break;
7640 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007641 case Instruction::Trunc:
7642 case Instruction::ZExt:
7643 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007644 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007645 // just return the source. There's no need to insert it because it is not
7646 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007647 if (I->getOperand(0)->getType() == Ty)
7648 return I->getOperand(0);
7649
Chris Lattner951626b2007-08-02 06:11:14 +00007650 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007651 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007652 Ty, I->getName());
7653 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007654 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007655 // TODO: Can handle more cases here.
7656 assert(0 && "Unreachable!");
7657 break;
7658 }
7659
7660 return InsertNewInstBefore(Res, *I);
7661}
7662
Reid Spencer3da59db2006-11-27 01:05:10 +00007663/// @brief Implement the transforms common to all CastInst visitors.
7664Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007665 Value *Src = CI.getOperand(0);
7666
Dan Gohman23d9d272007-05-11 21:10:54 +00007667 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007668 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007669 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007670 if (Instruction::CastOps opc =
7671 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7672 // The first cast (CSrc) is eliminable so we need to fix up or replace
7673 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007674 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007675 }
7676 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007677
Reid Spencer3da59db2006-11-27 01:05:10 +00007678 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007679 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7680 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7681 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007682
7683 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007684 if (isa<PHINode>(Src))
7685 if (Instruction *NV = FoldOpIntoPhi(CI))
7686 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007687
Reid Spencer3da59db2006-11-27 01:05:10 +00007688 return 0;
7689}
7690
Chris Lattnerd3e28342007-04-27 17:44:50 +00007691/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7692Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7693 Value *Src = CI.getOperand(0);
7694
Chris Lattnerd3e28342007-04-27 17:44:50 +00007695 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007696 // If casting the result of a getelementptr instruction with no offset, turn
7697 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007698 if (GEP->hasAllZeroIndices()) {
7699 // Changing the cast operand is usually not a good idea but it is safe
7700 // here because the pointer operand is being replaced with another
7701 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007702 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007703 CI.setOperand(0, GEP->getOperand(0));
7704 return &CI;
7705 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007706
7707 // If the GEP has a single use, and the base pointer is a bitcast, and the
7708 // GEP computes a constant offset, see if we can convert these three
7709 // instructions into fewer. This typically happens with unions and other
7710 // non-type-safe code.
7711 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7712 if (GEP->hasAllConstantIndices()) {
7713 // We are guaranteed to get a constant from EmitGEPOffset.
7714 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7715 int64_t Offset = OffsetV->getSExtValue();
7716
7717 // Get the base pointer input of the bitcast, and the type it points to.
7718 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7719 const Type *GEPIdxTy =
7720 cast<PointerType>(OrigBase->getType())->getElementType();
7721 if (GEPIdxTy->isSized()) {
7722 SmallVector<Value*, 8> NewIndices;
7723
Chris Lattnerc42e2262007-05-05 01:59:31 +00007724 // Start with the index over the outer type. Note that the type size
7725 // might be zero (even if the offset isn't zero) if the indexed type
7726 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007727 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007728 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007729 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007730 FirstIdx = Offset/TySize;
7731 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007732
Chris Lattnerc42e2262007-05-05 01:59:31 +00007733 // Handle silly modulus not returning values values [0..TySize).
7734 if (Offset < 0) {
7735 --FirstIdx;
7736 Offset += TySize;
7737 assert(Offset >= 0);
7738 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007739 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007740 }
7741
7742 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007743
7744 // Index into the types. If we fail, set OrigBase to null.
7745 while (Offset) {
7746 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7747 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007748 if (Offset < (int64_t)SL->getSizeInBytes()) {
7749 unsigned Elt = SL->getElementContainingOffset(Offset);
7750 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007751
Chris Lattner6b6aef82007-05-15 00:16:00 +00007752 Offset -= SL->getElementOffset(Elt);
7753 GEPIdxTy = STy->getElementType(Elt);
7754 } else {
7755 // Otherwise, we can't index into this, bail out.
7756 Offset = 0;
7757 OrigBase = 0;
7758 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007759 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7760 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007761 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007762 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7763 Offset %= EltSize;
7764 } else {
7765 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7766 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007767 GEPIdxTy = STy->getElementType();
7768 } else {
7769 // Otherwise, we can't index into this, bail out.
7770 Offset = 0;
7771 OrigBase = 0;
7772 }
7773 }
7774 if (OrigBase) {
7775 // If we were able to index down into an element, create the GEP
7776 // and bitcast the result. This eliminates one bitcast, potentially
7777 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007778 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7779 NewIndices.begin(),
7780 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007781 InsertNewInstBefore(NGEP, CI);
7782 NGEP->takeName(GEP);
7783
Chris Lattner9bc14642007-04-28 00:57:34 +00007784 if (isa<BitCastInst>(CI))
7785 return new BitCastInst(NGEP, CI.getType());
7786 assert(isa<PtrToIntInst>(CI));
7787 return new PtrToIntInst(NGEP, CI.getType());
7788 }
7789 }
7790 }
7791 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007792 }
7793
7794 return commonCastTransforms(CI);
7795}
7796
7797
7798
Chris Lattnerc739cd62007-03-03 05:27:34 +00007799/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7800/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007801/// cases.
7802/// @brief Implement the transforms common to CastInst with integer operands
7803Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7804 if (Instruction *Result = commonCastTransforms(CI))
7805 return Result;
7806
7807 Value *Src = CI.getOperand(0);
7808 const Type *SrcTy = Src->getType();
7809 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007810 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7811 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007812
Reid Spencer3da59db2006-11-27 01:05:10 +00007813 // See if we can simplify any instructions used by the LHS whose sole
7814 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007815 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7816 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007817 KnownZero, KnownOne))
7818 return &CI;
7819
7820 // If the source isn't an instruction or has more than one use then we
7821 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007822 Instruction *SrcI = dyn_cast<Instruction>(Src);
7823 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007824 return 0;
7825
Chris Lattnerc739cd62007-03-03 05:27:34 +00007826 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007827 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007828 if (!isa<BitCastInst>(CI) &&
7829 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007830 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007831 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007832 // eliminates the cast, so it is always a win. If this is a zero-extension,
7833 // we need to do an AND to maintain the clear top-part of the computation,
7834 // so we require that the input have eliminated at least one cast. If this
7835 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007836 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007837 bool DoXForm;
7838 switch (CI.getOpcode()) {
7839 default:
7840 // All the others use floating point so we shouldn't actually
7841 // get here because of the check above.
7842 assert(0 && "Unknown cast type");
7843 case Instruction::Trunc:
7844 DoXForm = true;
7845 break;
7846 case Instruction::ZExt:
7847 DoXForm = NumCastsRemoved >= 1;
7848 break;
7849 case Instruction::SExt:
7850 DoXForm = NumCastsRemoved >= 2;
7851 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007852 }
7853
7854 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007855 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7856 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007857 assert(Res->getType() == DestTy);
7858 switch (CI.getOpcode()) {
7859 default: assert(0 && "Unknown cast type!");
7860 case Instruction::Trunc:
7861 case Instruction::BitCast:
7862 // Just replace this cast with the result.
7863 return ReplaceInstUsesWith(CI, Res);
7864 case Instruction::ZExt: {
7865 // We need to emit an AND to clear the high bits.
7866 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007867 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7868 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007869 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007870 }
7871 case Instruction::SExt:
7872 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007873 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007874 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7875 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007876 }
7877 }
7878 }
7879
7880 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7881 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7882
7883 switch (SrcI->getOpcode()) {
7884 case Instruction::Add:
7885 case Instruction::Mul:
7886 case Instruction::And:
7887 case Instruction::Or:
7888 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007889 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007890 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7891 // Don't insert two casts if they cannot be eliminated. We allow
7892 // two casts to be inserted if the sizes are the same. This could
7893 // only be converting signedness, which is a noop.
7894 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007895 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7896 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007897 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007898 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7899 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007900 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007901 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007902 }
7903 }
7904
7905 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7906 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7907 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007908 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007909 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007910 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007911 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007912 }
7913 break;
7914 case Instruction::SDiv:
7915 case Instruction::UDiv:
7916 case Instruction::SRem:
7917 case Instruction::URem:
7918 // If we are just changing the sign, rewrite.
7919 if (DestBitSize == SrcBitSize) {
7920 // Don't insert two casts if they cannot be eliminated. We allow
7921 // two casts to be inserted if the sizes are the same. This could
7922 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007923 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7924 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007925 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7926 Op0, DestTy, SrcI);
7927 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7928 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007929 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007930 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7931 }
7932 }
7933 break;
7934
7935 case Instruction::Shl:
7936 // Allow changing the sign of the source operand. Do not allow
7937 // changing the size of the shift, UNLESS the shift amount is a
7938 // constant. We must not change variable sized shifts to a smaller
7939 // size, because it is undefined to shift more bits out than exist
7940 // in the value.
7941 if (DestBitSize == SrcBitSize ||
7942 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007943 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7944 Instruction::BitCast : Instruction::Trunc);
7945 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007946 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007947 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007948 }
7949 break;
7950 case Instruction::AShr:
7951 // If this is a signed shr, and if all bits shifted in are about to be
7952 // truncated off, turn it into an unsigned shr to allow greater
7953 // simplifications.
7954 if (DestBitSize < SrcBitSize &&
7955 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007956 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007957 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7958 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007959 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007960 }
7961 }
7962 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007963 }
7964 return 0;
7965}
7966
Chris Lattner8a9f5712007-04-11 06:57:46 +00007967Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007968 if (Instruction *Result = commonIntCastTransforms(CI))
7969 return Result;
7970
7971 Value *Src = CI.getOperand(0);
7972 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007973 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7974 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007975
7976 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7977 switch (SrcI->getOpcode()) {
7978 default: break;
7979 case Instruction::LShr:
7980 // We can shrink lshr to something smaller if we know the bits shifted in
7981 // are already zeros.
7982 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007983 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007984
7985 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007986 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007987 Value* SrcIOp0 = SrcI->getOperand(0);
7988 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007989 if (ShAmt >= DestBitWidth) // All zeros.
7990 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7991
7992 // Okay, we can shrink this. Truncate the input, then return a new
7993 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007994 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7995 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7996 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007997 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007998 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007999 } else { // This is a variable shr.
8000
8001 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8002 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8003 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00008004 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008005 Value *One = ConstantInt::get(SrcI->getType(), 1);
8006
Reid Spencer832254e2007-02-02 02:16:23 +00008007 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008008 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00008009 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008010 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008011 SrcI->getOperand(0),
8012 "tmp"), CI);
8013 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00008014 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008015 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008016 }
8017 break;
8018 }
8019 }
8020
8021 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008022}
8023
Evan Chengb98a10e2008-03-24 00:21:34 +00008024/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8025/// in order to eliminate the icmp.
8026Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8027 bool DoXform) {
8028 // If we are just checking for a icmp eq of a single bit and zext'ing it
8029 // to an integer, then shift the bit to the appropriate place and then
8030 // cast to integer to avoid the comparison.
8031 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8032 const APInt &Op1CV = Op1C->getValue();
8033
8034 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8035 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8036 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8037 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8038 if (!DoXform) return ICI;
8039
8040 Value *In = ICI->getOperand(0);
8041 Value *Sh = ConstantInt::get(In->getType(),
8042 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008043 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008044 In->getName()+".lobit"),
8045 CI);
8046 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008047 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008048 false/*ZExt*/, "tmp", &CI);
8049
8050 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8051 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008052 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008053 In->getName()+".not"),
8054 CI);
8055 }
8056
8057 return ReplaceInstUsesWith(CI, In);
8058 }
8059
8060
8061
8062 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8063 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8064 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8065 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8066 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8067 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8068 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8069 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8070 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8071 // This only works for EQ and NE
8072 ICI->isEquality()) {
8073 // If Op1C some other power of two, convert:
8074 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8075 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8076 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8077 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8078
8079 APInt KnownZeroMask(~KnownZero);
8080 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8081 if (!DoXform) return ICI;
8082
8083 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8084 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8085 // (X&4) == 2 --> false
8086 // (X&4) != 2 --> true
8087 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8088 Res = ConstantExpr::getZExt(Res, CI.getType());
8089 return ReplaceInstUsesWith(CI, Res);
8090 }
8091
8092 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8093 Value *In = ICI->getOperand(0);
8094 if (ShiftAmt) {
8095 // Perform a logical shr by shiftamt.
8096 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008097 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008098 ConstantInt::get(In->getType(), ShiftAmt),
8099 In->getName()+".lobit"), CI);
8100 }
8101
8102 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8103 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008104 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008105 InsertNewInstBefore(cast<Instruction>(In), CI);
8106 }
8107
8108 if (CI.getType() == In->getType())
8109 return ReplaceInstUsesWith(CI, In);
8110 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008111 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008112 }
8113 }
8114 }
8115
8116 return 0;
8117}
8118
Chris Lattner8a9f5712007-04-11 06:57:46 +00008119Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008120 // If one of the common conversion will work ..
8121 if (Instruction *Result = commonIntCastTransforms(CI))
8122 return Result;
8123
8124 Value *Src = CI.getOperand(0);
8125
8126 // If this is a cast of a cast
8127 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008128 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8129 // types and if the sizes are just right we can convert this into a logical
8130 // 'and' which will be much cheaper than the pair of casts.
8131 if (isa<TruncInst>(CSrc)) {
8132 // Get the sizes of the types involved
8133 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008134 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8135 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8136 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008137 // If we're actually extending zero bits and the trunc is a no-op
8138 if (MidSize < DstSize && SrcSize == DstSize) {
8139 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008140 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008141 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008142 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008143 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008144 // Unfortunately, if the type changed, we need to cast it back.
8145 if (And->getType() != CI.getType()) {
8146 And->setName(CSrc->getName()+".mask");
8147 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008148 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008149 }
8150 return And;
8151 }
8152 }
8153 }
8154
Evan Chengb98a10e2008-03-24 00:21:34 +00008155 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8156 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008157
Evan Chengb98a10e2008-03-24 00:21:34 +00008158 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8159 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8160 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8161 // of the (zext icmp) will be transformed.
8162 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8163 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8164 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8165 (transformZExtICmp(LHS, CI, false) ||
8166 transformZExtICmp(RHS, CI, false))) {
8167 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8168 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008169 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008170 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008171 }
8172
Reid Spencer3da59db2006-11-27 01:05:10 +00008173 return 0;
8174}
8175
Chris Lattner8a9f5712007-04-11 06:57:46 +00008176Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008177 if (Instruction *I = commonIntCastTransforms(CI))
8178 return I;
8179
Chris Lattner8a9f5712007-04-11 06:57:46 +00008180 Value *Src = CI.getOperand(0);
8181
8182 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8183 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8184 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8185 // If we are just checking for a icmp eq of a single bit and zext'ing it
8186 // to an integer, then shift the bit to the appropriate place and then
8187 // cast to integer to avoid the comparison.
8188 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8189 const APInt &Op1CV = Op1C->getValue();
8190
8191 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8192 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8193 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8194 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8195 Value *In = ICI->getOperand(0);
8196 Value *Sh = ConstantInt::get(In->getType(),
8197 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008198 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008199 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008200 CI);
8201 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008202 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008203 true/*SExt*/, "tmp", &CI);
8204
8205 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008206 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008207 In->getName()+".not"), CI);
8208
8209 return ReplaceInstUsesWith(CI, In);
8210 }
8211 }
8212 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008213
8214 // See if the value being truncated is already sign extended. If so, just
8215 // eliminate the trunc/sext pair.
8216 if (getOpcode(Src) == Instruction::Trunc) {
8217 Value *Op = cast<User>(Src)->getOperand(0);
8218 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8219 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8220 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8221 unsigned NumSignBits = ComputeNumSignBits(Op);
8222
8223 if (OpBits == DestBits) {
8224 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8225 // bits, it is already ready.
8226 if (NumSignBits > DestBits-MidBits)
8227 return ReplaceInstUsesWith(CI, Op);
8228 } else if (OpBits < DestBits) {
8229 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8230 // bits, just sext from i32.
8231 if (NumSignBits > OpBits-MidBits)
8232 return new SExtInst(Op, CI.getType(), "tmp");
8233 } else {
8234 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8235 // bits, just truncate to i32.
8236 if (NumSignBits > OpBits-MidBits)
8237 return new TruncInst(Op, CI.getType(), "tmp");
8238 }
8239 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008240
Chris Lattnerba417832007-04-11 06:12:58 +00008241 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008242}
8243
Chris Lattnerb7530652008-01-27 05:29:54 +00008244/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8245/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008246static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008247 APFloat F = CFP->getValueAPF();
8248 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008249 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008250 return 0;
8251}
8252
8253/// LookThroughFPExtensions - If this is an fp extension instruction, look
8254/// through it until we get the source value.
8255static Value *LookThroughFPExtensions(Value *V) {
8256 if (Instruction *I = dyn_cast<Instruction>(V))
8257 if (I->getOpcode() == Instruction::FPExt)
8258 return LookThroughFPExtensions(I->getOperand(0));
8259
8260 // If this value is a constant, return the constant in the smallest FP type
8261 // that can accurately represent it. This allows us to turn
8262 // (float)((double)X+2.0) into x+2.0f.
8263 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8264 if (CFP->getType() == Type::PPC_FP128Ty)
8265 return V; // No constant folding of this.
8266 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008267 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008268 return V;
8269 if (CFP->getType() == Type::DoubleTy)
8270 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008271 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008272 return V;
8273 // Don't try to shrink to various long double types.
8274 }
8275
8276 return V;
8277}
8278
8279Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8280 if (Instruction *I = commonCastTransforms(CI))
8281 return I;
8282
8283 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8284 // smaller than the destination type, we can eliminate the truncate by doing
8285 // the add as the smaller type. This applies to add/sub/mul/div as well as
8286 // many builtins (sqrt, etc).
8287 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8288 if (OpI && OpI->hasOneUse()) {
8289 switch (OpI->getOpcode()) {
8290 default: break;
8291 case Instruction::Add:
8292 case Instruction::Sub:
8293 case Instruction::Mul:
8294 case Instruction::FDiv:
8295 case Instruction::FRem:
8296 const Type *SrcTy = OpI->getType();
8297 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8298 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8299 if (LHSTrunc->getType() != SrcTy &&
8300 RHSTrunc->getType() != SrcTy) {
8301 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8302 // If the source types were both smaller than the destination type of
8303 // the cast, do this xform.
8304 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8305 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8306 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8307 CI.getType(), CI);
8308 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8309 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008310 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008311 }
8312 }
8313 break;
8314 }
8315 }
8316 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008317}
8318
8319Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8320 return commonCastTransforms(CI);
8321}
8322
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008323Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8324 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8325 // mantissa to accurately represent all values of X. For example, do not
8326 // do this with i64->float->i64.
8327 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8328 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8329 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008330 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008331 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8332
8333 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008334}
8335
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008336Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8337 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8338 // mantissa to accurately represent all values of X. For example, do not
8339 // do this with i64->float->i64.
8340 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8341 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8342 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008343 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008344 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8345
8346 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008347}
8348
8349Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8350 return commonCastTransforms(CI);
8351}
8352
8353Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8354 return commonCastTransforms(CI);
8355}
8356
8357Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008358 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008359}
8360
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008361Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8362 if (Instruction *I = commonCastTransforms(CI))
8363 return I;
8364
8365 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8366 if (!DestPointee->isSized()) return 0;
8367
8368 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8369 ConstantInt *Cst;
8370 Value *X;
8371 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8372 m_ConstantInt(Cst)))) {
8373 // If the source and destination operands have the same type, see if this
8374 // is a single-index GEP.
8375 if (X->getType() == CI.getType()) {
8376 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008377 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008378
8379 // Convert the constant to intptr type.
8380 APInt Offset = Cst->getValue();
8381 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8382
8383 // If Offset is evenly divisible by Size, we can do this xform.
8384 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8385 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008386 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008387 }
8388 }
8389 // TODO: Could handle other cases, e.g. where add is indexing into field of
8390 // struct etc.
8391 } else if (CI.getOperand(0)->hasOneUse() &&
8392 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8393 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8394 // "inttoptr+GEP" instead of "add+intptr".
8395
8396 // Get the size of the pointee type.
8397 uint64_t Size = TD->getABITypeSize(DestPointee);
8398
8399 // Convert the constant to intptr type.
8400 APInt Offset = Cst->getValue();
8401 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8402
8403 // If Offset is evenly divisible by Size, we can do this xform.
8404 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8405 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8406
8407 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8408 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008409 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008410 }
8411 }
8412 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008413}
8414
Chris Lattnerd3e28342007-04-27 17:44:50 +00008415Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008416 // If the operands are integer typed then apply the integer transforms,
8417 // otherwise just apply the common ones.
8418 Value *Src = CI.getOperand(0);
8419 const Type *SrcTy = Src->getType();
8420 const Type *DestTy = CI.getType();
8421
Chris Lattner42a75512007-01-15 02:27:26 +00008422 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008423 if (Instruction *Result = commonIntCastTransforms(CI))
8424 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008425 } else if (isa<PointerType>(SrcTy)) {
8426 if (Instruction *I = commonPointerCastTransforms(CI))
8427 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008428 } else {
8429 if (Instruction *Result = commonCastTransforms(CI))
8430 return Result;
8431 }
8432
8433
8434 // Get rid of casts from one type to the same type. These are useless and can
8435 // be replaced by the operand.
8436 if (DestTy == Src->getType())
8437 return ReplaceInstUsesWith(CI, Src);
8438
Reid Spencer3da59db2006-11-27 01:05:10 +00008439 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008440 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8441 const Type *DstElTy = DstPTy->getElementType();
8442 const Type *SrcElTy = SrcPTy->getElementType();
8443
Nate Begeman83ad90a2008-03-31 00:22:16 +00008444 // If the address spaces don't match, don't eliminate the bitcast, which is
8445 // required for changing types.
8446 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8447 return 0;
8448
Chris Lattnerd3e28342007-04-27 17:44:50 +00008449 // If we are casting a malloc or alloca to a pointer to a type of the same
8450 // size, rewrite the allocation instruction to allocate the "right" type.
8451 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8452 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8453 return V;
8454
Chris Lattnerd717c182007-05-05 22:32:24 +00008455 // If the source and destination are pointers, and this cast is equivalent
8456 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008457 // This can enhance SROA and other transforms that want type-safe pointers.
8458 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8459 unsigned NumZeros = 0;
8460 while (SrcElTy != DstElTy &&
8461 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8462 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8463 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8464 ++NumZeros;
8465 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008466
Chris Lattnerd3e28342007-04-27 17:44:50 +00008467 // If we found a path from the src to dest, create the getelementptr now.
8468 if (SrcElTy == DstElTy) {
8469 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008470 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8471 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008472 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008473 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008474
Reid Spencer3da59db2006-11-27 01:05:10 +00008475 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8476 if (SVI->hasOneUse()) {
8477 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8478 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008479 if (isa<VectorType>(DestTy) &&
8480 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008481 SVI->getType()->getNumElements()) {
8482 CastInst *Tmp;
8483 // If either of the operands is a cast from CI.getType(), then
8484 // evaluating the shuffle in the casted destination's type will allow
8485 // us to eliminate at least one cast.
8486 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8487 Tmp->getOperand(0)->getType() == DestTy) ||
8488 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8489 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008490 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8491 SVI->getOperand(0), DestTy, &CI);
8492 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8493 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008494 // Return a new shuffle vector. Use the same element ID's, as we
8495 // know the vector types match #elts.
8496 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008497 }
8498 }
8499 }
8500 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008501 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008502}
8503
Chris Lattnere576b912004-04-09 23:46:01 +00008504/// GetSelectFoldableOperands - We want to turn code that looks like this:
8505/// %C = or %A, %B
8506/// %D = select %cond, %C, %A
8507/// into:
8508/// %C = select %cond, %B, 0
8509/// %D = or %A, %C
8510///
8511/// Assuming that the specified instruction is an operand to the select, return
8512/// a bitmask indicating which operands of this instruction are foldable if they
8513/// equal the other incoming value of the select.
8514///
8515static unsigned GetSelectFoldableOperands(Instruction *I) {
8516 switch (I->getOpcode()) {
8517 case Instruction::Add:
8518 case Instruction::Mul:
8519 case Instruction::And:
8520 case Instruction::Or:
8521 case Instruction::Xor:
8522 return 3; // Can fold through either operand.
8523 case Instruction::Sub: // Can only fold on the amount subtracted.
8524 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008525 case Instruction::LShr:
8526 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008527 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008528 default:
8529 return 0; // Cannot fold
8530 }
8531}
8532
8533/// GetSelectFoldableConstant - For the same transformation as the previous
8534/// function, return the identity constant that goes into the select.
8535static Constant *GetSelectFoldableConstant(Instruction *I) {
8536 switch (I->getOpcode()) {
8537 default: assert(0 && "This cannot happen!"); abort();
8538 case Instruction::Add:
8539 case Instruction::Sub:
8540 case Instruction::Or:
8541 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008542 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008543 case Instruction::LShr:
8544 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008545 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008546 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008547 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008548 case Instruction::Mul:
8549 return ConstantInt::get(I->getType(), 1);
8550 }
8551}
8552
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008553/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8554/// have the same opcode and only one use each. Try to simplify this.
8555Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8556 Instruction *FI) {
8557 if (TI->getNumOperands() == 1) {
8558 // If this is a non-volatile load or a cast from the same type,
8559 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008560 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008561 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8562 return 0;
8563 } else {
8564 return 0; // unknown unary op.
8565 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008566
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008567 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008568 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8569 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008570 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008571 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008572 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008573 }
8574
Reid Spencer832254e2007-02-02 02:16:23 +00008575 // Only handle binary operators here.
8576 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008577 return 0;
8578
8579 // Figure out if the operations have any operands in common.
8580 Value *MatchOp, *OtherOpT, *OtherOpF;
8581 bool MatchIsOpZero;
8582 if (TI->getOperand(0) == FI->getOperand(0)) {
8583 MatchOp = TI->getOperand(0);
8584 OtherOpT = TI->getOperand(1);
8585 OtherOpF = FI->getOperand(1);
8586 MatchIsOpZero = true;
8587 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8588 MatchOp = TI->getOperand(1);
8589 OtherOpT = TI->getOperand(0);
8590 OtherOpF = FI->getOperand(0);
8591 MatchIsOpZero = false;
8592 } else if (!TI->isCommutative()) {
8593 return 0;
8594 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8595 MatchOp = TI->getOperand(0);
8596 OtherOpT = TI->getOperand(1);
8597 OtherOpF = FI->getOperand(0);
8598 MatchIsOpZero = true;
8599 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8600 MatchOp = TI->getOperand(1);
8601 OtherOpT = TI->getOperand(0);
8602 OtherOpF = FI->getOperand(1);
8603 MatchIsOpZero = true;
8604 } else {
8605 return 0;
8606 }
8607
8608 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008609 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8610 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008611 InsertNewInstBefore(NewSI, SI);
8612
8613 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8614 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008615 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008616 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008617 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008618 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008619 assert(0 && "Shouldn't get here");
8620 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008621}
8622
Chris Lattner3d69f462004-03-12 05:52:32 +00008623Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008624 Value *CondVal = SI.getCondition();
8625 Value *TrueVal = SI.getTrueValue();
8626 Value *FalseVal = SI.getFalseValue();
8627
8628 // select true, X, Y -> X
8629 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008630 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008631 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008632
8633 // select C, X, X -> X
8634 if (TrueVal == FalseVal)
8635 return ReplaceInstUsesWith(SI, TrueVal);
8636
Chris Lattnere87597f2004-10-16 18:11:37 +00008637 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8638 return ReplaceInstUsesWith(SI, FalseVal);
8639 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8640 return ReplaceInstUsesWith(SI, TrueVal);
8641 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8642 if (isa<Constant>(TrueVal))
8643 return ReplaceInstUsesWith(SI, TrueVal);
8644 else
8645 return ReplaceInstUsesWith(SI, FalseVal);
8646 }
8647
Reid Spencer4fe16d62007-01-11 18:21:29 +00008648 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008649 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008650 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008651 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008652 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008653 } else {
8654 // Change: A = select B, false, C --> A = and !B, C
8655 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008656 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008657 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008658 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008659 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008660 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008661 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008662 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008663 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008664 } else {
8665 // Change: A = select B, C, true --> A = or !B, C
8666 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008667 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008668 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008669 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008670 }
8671 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008672
8673 // select a, b, a -> a&b
8674 // select a, a, b -> a|b
8675 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008676 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008677 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008678 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008679 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008680
Chris Lattner2eefe512004-04-09 19:05:30 +00008681 // Selecting between two integer constants?
8682 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8683 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008684 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008685 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008686 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008687 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008688 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008689 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008690 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008691 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008692 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008693 }
Chris Lattnerba417832007-04-11 06:12:58 +00008694
8695 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008696
Reid Spencere4d87aa2006-12-23 06:05:41 +00008697 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008698
Reid Spencere4d87aa2006-12-23 06:05:41 +00008699 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008700 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008701 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008702 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008703 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008704 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008705 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008706 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008707 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008708 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008709 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008710 InsertNewInstBefore(SRA, SI);
8711
Reid Spencer3da59db2006-11-27 01:05:10 +00008712 // Finally, convert to the type of the select RHS. We figure out
8713 // if this requires a SExt, Trunc or BitCast based on the sizes.
8714 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008715 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8716 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008717 if (SRASize < SISize)
8718 opc = Instruction::SExt;
8719 else if (SRASize > SISize)
8720 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008721 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008722 }
8723 }
8724
8725
8726 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008727 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008728 // non-constant value, eliminate this whole mess. This corresponds to
8729 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008730 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008731 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008732 cast<Constant>(IC->getOperand(1))->isNullValue())
8733 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8734 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008735 isa<ConstantInt>(ICA->getOperand(1)) &&
8736 (ICA->getOperand(1) == TrueValC ||
8737 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008738 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8739 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008740 // know whether we have a icmp_ne or icmp_eq and whether the
8741 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008742 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008743 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008744 Value *V = ICA;
8745 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008746 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008747 Instruction::Xor, V, ICA->getOperand(1)), SI);
8748 return ReplaceInstUsesWith(SI, V);
8749 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008750 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008751 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008752
8753 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008754 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8755 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008756 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008757 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8758 // This is not safe in general for floating point:
8759 // consider X== -0, Y== +0.
8760 // It becomes safe if either operand is a nonzero constant.
8761 ConstantFP *CFPt, *CFPf;
8762 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8763 !CFPt->getValueAPF().isZero()) ||
8764 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8765 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008766 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008767 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008768 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008769 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008770 return ReplaceInstUsesWith(SI, TrueVal);
8771 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8772
Reid Spencere4d87aa2006-12-23 06:05:41 +00008773 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008774 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008775 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8776 // This is not safe in general for floating point:
8777 // consider X== -0, Y== +0.
8778 // It becomes safe if either operand is a nonzero constant.
8779 ConstantFP *CFPt, *CFPf;
8780 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8781 !CFPt->getValueAPF().isZero()) ||
8782 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8783 !CFPf->getValueAPF().isZero()))
8784 return ReplaceInstUsesWith(SI, FalseVal);
8785 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008786 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008787 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8788 return ReplaceInstUsesWith(SI, TrueVal);
8789 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8790 }
8791 }
8792
8793 // See if we are selecting two values based on a comparison of the two values.
8794 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8795 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8796 // Transform (X == Y) ? X : Y -> Y
8797 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8798 return ReplaceInstUsesWith(SI, FalseVal);
8799 // Transform (X != Y) ? X : Y -> X
8800 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8801 return ReplaceInstUsesWith(SI, TrueVal);
8802 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8803
8804 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8805 // Transform (X == Y) ? Y : X -> X
8806 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8807 return ReplaceInstUsesWith(SI, FalseVal);
8808 // Transform (X != Y) ? Y : X -> Y
8809 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008810 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008811 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8812 }
8813 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008814
Chris Lattner87875da2005-01-13 22:52:24 +00008815 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8816 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8817 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008818 Instruction *AddOp = 0, *SubOp = 0;
8819
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008820 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8821 if (TI->getOpcode() == FI->getOpcode())
8822 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8823 return IV;
8824
8825 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8826 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008827 if (TI->getOpcode() == Instruction::Sub &&
8828 FI->getOpcode() == Instruction::Add) {
8829 AddOp = FI; SubOp = TI;
8830 } else if (FI->getOpcode() == Instruction::Sub &&
8831 TI->getOpcode() == Instruction::Add) {
8832 AddOp = TI; SubOp = FI;
8833 }
8834
8835 if (AddOp) {
8836 Value *OtherAddOp = 0;
8837 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8838 OtherAddOp = AddOp->getOperand(1);
8839 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8840 OtherAddOp = AddOp->getOperand(0);
8841 }
8842
8843 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008844 // So at this point we know we have (Y -> OtherAddOp):
8845 // select C, (add X, Y), (sub X, Z)
8846 Value *NegVal; // Compute -Z
8847 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8848 NegVal = ConstantExpr::getNeg(C);
8849 } else {
8850 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008851 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008852 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008853
8854 Value *NewTrueOp = OtherAddOp;
8855 Value *NewFalseOp = NegVal;
8856 if (AddOp != TI)
8857 std::swap(NewTrueOp, NewFalseOp);
8858 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008859 SelectInst::Create(CondVal, NewTrueOp,
8860 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008861
8862 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008863 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008864 }
8865 }
8866 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008867
Chris Lattnere576b912004-04-09 23:46:01 +00008868 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008869 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008870 // See the comment above GetSelectFoldableOperands for a description of the
8871 // transformation we are doing here.
8872 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8873 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8874 !isa<Constant>(FalseVal))
8875 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8876 unsigned OpToFold = 0;
8877 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8878 OpToFold = 1;
8879 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8880 OpToFold = 2;
8881 }
8882
8883 if (OpToFold) {
8884 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008885 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008886 SelectInst::Create(SI.getCondition(),
8887 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008888 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008889 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008890 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008891 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008892 else {
8893 assert(0 && "Unknown instruction!!");
8894 }
8895 }
8896 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008897
Chris Lattnere576b912004-04-09 23:46:01 +00008898 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8899 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8900 !isa<Constant>(TrueVal))
8901 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8902 unsigned OpToFold = 0;
8903 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8904 OpToFold = 1;
8905 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8906 OpToFold = 2;
8907 }
8908
8909 if (OpToFold) {
8910 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008911 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008912 SelectInst::Create(SI.getCondition(), C,
8913 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008914 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008915 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008916 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008917 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008918 else
Chris Lattnere576b912004-04-09 23:46:01 +00008919 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008920 }
8921 }
8922 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008923
8924 if (BinaryOperator::isNot(CondVal)) {
8925 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8926 SI.setOperand(1, FalseVal);
8927 SI.setOperand(2, TrueVal);
8928 return &SI;
8929 }
8930
Chris Lattner3d69f462004-03-12 05:52:32 +00008931 return 0;
8932}
8933
Dan Gohmaneee962e2008-04-10 18:43:06 +00008934/// EnforceKnownAlignment - If the specified pointer points to an object that
8935/// we control, modify the object's alignment to PrefAlign. This isn't
8936/// often possible though. If alignment is important, a more reliable approach
8937/// is to simply align all global variables and allocation instructions to
8938/// their preferred alignment from the beginning.
8939///
8940static unsigned EnforceKnownAlignment(Value *V,
8941 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008942
Dan Gohmaneee962e2008-04-10 18:43:06 +00008943 User *U = dyn_cast<User>(V);
8944 if (!U) return Align;
8945
8946 switch (getOpcode(U)) {
8947 default: break;
8948 case Instruction::BitCast:
8949 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8950 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008951 // If all indexes are zero, it is just the alignment of the base pointer.
8952 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008953 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8954 if (!isa<Constant>(U->getOperand(i)) ||
8955 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008956 AllZeroOperands = false;
8957 break;
8958 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008959
8960 if (AllZeroOperands) {
8961 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008962 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008963 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008964 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008965 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008966 }
8967
8968 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8969 // If there is a large requested alignment and we can, bump up the alignment
8970 // of the global.
8971 if (!GV->isDeclaration()) {
8972 GV->setAlignment(PrefAlign);
8973 Align = PrefAlign;
8974 }
8975 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8976 // If there is a requested alignment and if this is an alloca, round up. We
8977 // don't do this for malloc, because some systems can't respect the request.
8978 if (isa<AllocaInst>(AI)) {
8979 AI->setAlignment(PrefAlign);
8980 Align = PrefAlign;
8981 }
8982 }
8983
8984 return Align;
8985}
8986
8987/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8988/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8989/// and it is more than the alignment of the ultimate object, see if we can
8990/// increase the alignment of the ultimate object, making this check succeed.
8991unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8992 unsigned PrefAlign) {
8993 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8994 sizeof(PrefAlign) * CHAR_BIT;
8995 APInt Mask = APInt::getAllOnesValue(BitWidth);
8996 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8997 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8998 unsigned TrailZ = KnownZero.countTrailingOnes();
8999 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9000
9001 if (PrefAlign > Align)
9002 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9003
9004 // We don't need to make any adjustment.
9005 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009006}
9007
Chris Lattnerf497b022008-01-13 23:50:23 +00009008Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009009 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9010 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009011 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9012 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9013
9014 if (CopyAlign < MinAlign) {
9015 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9016 return MI;
9017 }
9018
9019 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9020 // load/store.
9021 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9022 if (MemOpLength == 0) return 0;
9023
Chris Lattner37ac6082008-01-14 00:28:35 +00009024 // Source and destination pointer types are always "i8*" for intrinsic. See
9025 // if the size is something we can handle with a single primitive load/store.
9026 // A single load+store correctly handles overlapping memory in the memmove
9027 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009028 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009029 if (Size == 0) return MI; // Delete this mem transfer.
9030
9031 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009032 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009033
Chris Lattner37ac6082008-01-14 00:28:35 +00009034 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009035 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009036
9037 // Memcpy forces the use of i8* for the source and destination. That means
9038 // that if you're using memcpy to move one double around, you'll get a cast
9039 // from double* to i8*. We'd much rather use a double load+store rather than
9040 // an i64 load+store, here because this improves the odds that the source or
9041 // dest address will be promotable. See if we can find a better type than the
9042 // integer datatype.
9043 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9044 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9045 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9046 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9047 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009048 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009049 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9050 if (STy->getNumElements() == 1)
9051 SrcETy = STy->getElementType(0);
9052 else
9053 break;
9054 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9055 if (ATy->getNumElements() == 1)
9056 SrcETy = ATy->getElementType();
9057 else
9058 break;
9059 } else
9060 break;
9061 }
9062
Dan Gohman8f8e2692008-05-23 01:52:21 +00009063 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009064 NewPtrTy = PointerType::getUnqual(SrcETy);
9065 }
9066 }
9067
9068
Chris Lattnerf497b022008-01-13 23:50:23 +00009069 // If the memcpy/memmove provides better alignment info than we can
9070 // infer, use it.
9071 SrcAlign = std::max(SrcAlign, CopyAlign);
9072 DstAlign = std::max(DstAlign, CopyAlign);
9073
9074 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9075 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009076 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9077 InsertNewInstBefore(L, *MI);
9078 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9079
9080 // Set the size of the copy to 0, it will be deleted on the next iteration.
9081 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9082 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009083}
Chris Lattner3d69f462004-03-12 05:52:32 +00009084
Chris Lattner69ea9d22008-04-30 06:39:11 +00009085Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9086 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9087 if (MI->getAlignment()->getZExtValue() < Alignment) {
9088 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9089 return MI;
9090 }
9091
9092 // Extract the length and alignment and fill if they are constant.
9093 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9094 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9095 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9096 return 0;
9097 uint64_t Len = LenC->getZExtValue();
9098 Alignment = MI->getAlignment()->getZExtValue();
9099
9100 // If the length is zero, this is a no-op
9101 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9102
9103 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9104 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9105 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9106
9107 Value *Dest = MI->getDest();
9108 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9109
9110 // Alignment 0 is identity for alignment 1 for memset, but not store.
9111 if (Alignment == 0) Alignment = 1;
9112
9113 // Extract the fill value and store.
9114 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9115 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9116 Alignment), *MI);
9117
9118 // Set the size of the copy to 0, it will be deleted on the next iteration.
9119 MI->setLength(Constant::getNullValue(LenC->getType()));
9120 return MI;
9121 }
9122
9123 return 0;
9124}
9125
9126
Chris Lattner8b0ea312006-01-13 20:11:04 +00009127/// visitCallInst - CallInst simplification. This mostly only handles folding
9128/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9129/// the heavy lifting.
9130///
Chris Lattner9fe38862003-06-19 17:00:31 +00009131Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009132 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9133 if (!II) return visitCallSite(&CI);
9134
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009135 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9136 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009137 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009138 bool Changed = false;
9139
9140 // memmove/cpy/set of zero bytes is a noop.
9141 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9142 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9143
Chris Lattner35b9e482004-10-12 04:52:52 +00009144 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009145 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009146 // Replace the instruction with just byte operations. We would
9147 // transform other cases to loads/stores, but we don't know if
9148 // alignment is sufficient.
9149 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009150 }
9151
Chris Lattner35b9e482004-10-12 04:52:52 +00009152 // If we have a memmove and the source operation is a constant global,
9153 // then the source and dest pointers can't alias, so we can change this
9154 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009155 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009156 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9157 if (GVSrc->isConstant()) {
9158 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009159 Intrinsic::ID MemCpyID;
9160 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9161 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009162 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009163 MemCpyID = Intrinsic::memcpy_i64;
9164 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009165 Changed = true;
9166 }
Chris Lattnera935db82008-05-28 05:30:41 +00009167
9168 // memmove(x,x,size) -> noop.
9169 if (MMI->getSource() == MMI->getDest())
9170 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009171 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009172
Chris Lattner95a959d2006-03-06 20:18:44 +00009173 // If we can determine a pointer alignment that is bigger than currently
9174 // set, update the alignment.
9175 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009176 if (Instruction *I = SimplifyMemTransfer(MI))
9177 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009178 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9179 if (Instruction *I = SimplifyMemSet(MSI))
9180 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009181 }
9182
Chris Lattner8b0ea312006-01-13 20:11:04 +00009183 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009184 } else {
9185 switch (II->getIntrinsicID()) {
9186 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009187 case Intrinsic::ppc_altivec_lvx:
9188 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009189 case Intrinsic::x86_sse_loadu_ps:
9190 case Intrinsic::x86_sse2_loadu_pd:
9191 case Intrinsic::x86_sse2_loadu_dq:
9192 // Turn PPC lvx -> load if the pointer is known aligned.
9193 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009194 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009195 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9196 PointerType::getUnqual(II->getType()),
9197 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009198 return new LoadInst(Ptr);
9199 }
9200 break;
9201 case Intrinsic::ppc_altivec_stvx:
9202 case Intrinsic::ppc_altivec_stvxl:
9203 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009204 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009205 const Type *OpPtrTy =
9206 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009207 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009208 return new StoreInst(II->getOperand(1), Ptr);
9209 }
9210 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009211 case Intrinsic::x86_sse_storeu_ps:
9212 case Intrinsic::x86_sse2_storeu_pd:
9213 case Intrinsic::x86_sse2_storeu_dq:
9214 case Intrinsic::x86_sse2_storel_dq:
9215 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009216 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009217 const Type *OpPtrTy =
9218 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009219 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009220 return new StoreInst(II->getOperand(2), Ptr);
9221 }
9222 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009223
9224 case Intrinsic::x86_sse_cvttss2si: {
9225 // These intrinsics only demands the 0th element of its input vector. If
9226 // we can simplify the input based on that, do so now.
9227 uint64_t UndefElts;
9228 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9229 UndefElts)) {
9230 II->setOperand(1, V);
9231 return II;
9232 }
9233 break;
9234 }
9235
Chris Lattnere2ed0572006-04-06 19:19:17 +00009236 case Intrinsic::ppc_altivec_vperm:
9237 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009238 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009239 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9240
9241 // Check that all of the elements are integer constants or undefs.
9242 bool AllEltsOk = true;
9243 for (unsigned i = 0; i != 16; ++i) {
9244 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9245 !isa<UndefValue>(Mask->getOperand(i))) {
9246 AllEltsOk = false;
9247 break;
9248 }
9249 }
9250
9251 if (AllEltsOk) {
9252 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009253 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9254 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009255 Value *Result = UndefValue::get(Op0->getType());
9256
9257 // Only extract each element once.
9258 Value *ExtractedElts[32];
9259 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9260
9261 for (unsigned i = 0; i != 16; ++i) {
9262 if (isa<UndefValue>(Mask->getOperand(i)))
9263 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009264 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009265 Idx &= 31; // Match the hardware behavior.
9266
9267 if (ExtractedElts[Idx] == 0) {
9268 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009269 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009270 InsertNewInstBefore(Elt, CI);
9271 ExtractedElts[Idx] = Elt;
9272 }
9273
9274 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009275 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9276 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009277 InsertNewInstBefore(cast<Instruction>(Result), CI);
9278 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009279 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009280 }
9281 }
9282 break;
9283
Chris Lattnera728ddc2006-01-13 21:28:09 +00009284 case Intrinsic::stackrestore: {
9285 // If the save is right next to the restore, remove the restore. This can
9286 // happen when variable allocas are DCE'd.
9287 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9288 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9289 BasicBlock::iterator BI = SS;
9290 if (&*++BI == II)
9291 return EraseInstFromFunction(CI);
9292 }
9293 }
9294
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009295 // Scan down this block to see if there is another stack restore in the
9296 // same block without an intervening call/alloca.
9297 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009298 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009299 bool CannotRemove = false;
9300 for (++BI; &*BI != TI; ++BI) {
9301 if (isa<AllocaInst>(BI)) {
9302 CannotRemove = true;
9303 break;
9304 }
9305 if (isa<CallInst>(BI)) {
9306 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009307 CannotRemove = true;
9308 break;
9309 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009310 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009311 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009312 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009313 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009314
9315 // If the stack restore is in a return/unwind block and if there are no
9316 // allocas or calls between the restore and the return, nuke the restore.
9317 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9318 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009319 break;
9320 }
9321 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009322 }
9323
Chris Lattner8b0ea312006-01-13 20:11:04 +00009324 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009325}
9326
9327// InvokeInst simplification
9328//
9329Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009330 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009331}
9332
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009333/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9334/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009335static bool isSafeToEliminateVarargsCast(const CallSite CS,
9336 const CastInst * const CI,
9337 const TargetData * const TD,
9338 const int ix) {
9339 if (!CI->isLosslessCast())
9340 return false;
9341
9342 // The size of ByVal arguments is derived from the type, so we
9343 // can't change to a type with a different size. If the size were
9344 // passed explicitly we could avoid this check.
9345 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9346 return true;
9347
9348 const Type* SrcTy =
9349 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9350 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9351 if (!SrcTy->isSized() || !DstTy->isSized())
9352 return false;
9353 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9354 return false;
9355 return true;
9356}
9357
Chris Lattnera44d8a22003-10-07 22:32:43 +00009358// visitCallSite - Improvements for call and invoke instructions.
9359//
9360Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009361 bool Changed = false;
9362
9363 // If the callee is a constexpr cast of a function, attempt to move the cast
9364 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009365 if (transformConstExprCastCall(CS)) return 0;
9366
Chris Lattner6c266db2003-10-07 22:54:13 +00009367 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009368
Chris Lattner08b22ec2005-05-13 07:09:09 +00009369 if (Function *CalleeF = dyn_cast<Function>(Callee))
9370 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9371 Instruction *OldCall = CS.getInstruction();
9372 // If the call and callee calling conventions don't match, this call must
9373 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009374 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009375 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9376 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009377 if (!OldCall->use_empty())
9378 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9379 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9380 return EraseInstFromFunction(*OldCall);
9381 return 0;
9382 }
9383
Chris Lattner17be6352004-10-18 02:59:09 +00009384 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9385 // This instruction is not reachable, just remove it. We insert a store to
9386 // undef so that we know that this code is not reachable, despite the fact
9387 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009388 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009389 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009390 CS.getInstruction());
9391
9392 if (!CS.getInstruction()->use_empty())
9393 CS.getInstruction()->
9394 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9395
9396 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9397 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009398 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9399 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009400 }
Chris Lattner17be6352004-10-18 02:59:09 +00009401 return EraseInstFromFunction(*CS.getInstruction());
9402 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009403
Duncan Sandscdb6d922007-09-17 10:26:40 +00009404 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9405 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9406 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9407 return transformCallThroughTrampoline(CS);
9408
Chris Lattner6c266db2003-10-07 22:54:13 +00009409 const PointerType *PTy = cast<PointerType>(Callee->getType());
9410 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9411 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009412 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009413 // See if we can optimize any arguments passed through the varargs area of
9414 // the call.
9415 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009416 E = CS.arg_end(); I != E; ++I, ++ix) {
9417 CastInst *CI = dyn_cast<CastInst>(*I);
9418 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9419 *I = CI->getOperand(0);
9420 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009421 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009422 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009423 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009424
Duncan Sandsf0c33542007-12-19 21:13:37 +00009425 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009426 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009427 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009428 Changed = true;
9429 }
9430
Chris Lattner6c266db2003-10-07 22:54:13 +00009431 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009432}
9433
Chris Lattner9fe38862003-06-19 17:00:31 +00009434// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9435// attempt to move the cast to the arguments of the call/invoke.
9436//
9437bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9438 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9439 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009440 if (CE->getOpcode() != Instruction::BitCast ||
9441 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009442 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009443 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009444 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009445 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009446
9447 // Okay, this is a cast from a function to a different type. Unless doing so
9448 // would cause a type conversion of one of our arguments, change this call to
9449 // be a direct call with arguments casted to the appropriate types.
9450 //
9451 const FunctionType *FT = Callee->getFunctionType();
9452 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009453 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009454
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009455 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009456 return false; // TODO: Handle multiple return values.
9457
Chris Lattnerf78616b2004-01-14 06:06:08 +00009458 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009459 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009460 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009461 // Conversion is ok if changing from one pointer type to another or from
9462 // a pointer to an integer of the same size.
9463 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9464 isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
Chris Lattnerec479922007-01-06 02:09:32 +00009465 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009466
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009467 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009468 // void -> non-void is handled specially
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009469 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009470 return false; // Cannot transform this return value.
9471
Chris Lattner58d74912008-03-12 17:45:29 +00009472 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9473 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009474 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009475 return false; // Attribute not compatible with transformed value.
9476 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009477
Chris Lattnerf78616b2004-01-14 06:06:08 +00009478 // If the callsite is an invoke instruction, and the return value is used by
9479 // a PHI node in a successor, we cannot change the return type of the call
9480 // because there is no place to put the cast instruction (without breaking
9481 // the critical edge). Bail out in this case.
9482 if (!Caller->use_empty())
9483 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9484 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9485 UI != E; ++UI)
9486 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9487 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009488 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009489 return false;
9490 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009491
9492 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9493 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009494
Chris Lattner9fe38862003-06-19 17:00:31 +00009495 CallSite::arg_iterator AI = CS.arg_begin();
9496 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9497 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009498 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009499
9500 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009501 return false; // Cannot transform this parameter value.
9502
Chris Lattner58d74912008-03-12 17:45:29 +00009503 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9504 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009505
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009506 // Converting from one pointer type to another or between a pointer and an
9507 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +00009508 bool isConvertible = ActTy == ParamTy ||
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009509 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9510 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Reid Spencer5cbf9852007-01-30 20:08:39 +00009511 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009512 }
9513
9514 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009515 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009516 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009517
Chris Lattner58d74912008-03-12 17:45:29 +00009518 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9519 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009520 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009521 // won't be dropping them. Check that these extra arguments have attributes
9522 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009523 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9524 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009525 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009526 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009527 if (PAttrs & ParamAttr::VarArgsIncompatible)
9528 return false;
9529 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009530
Chris Lattner9fe38862003-06-19 17:00:31 +00009531 // Okay, we decided that this is a safe thing to do: go ahead and start
9532 // inserting cast instructions as necessary...
9533 std::vector<Value*> Args;
9534 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009535 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009536 attrVec.reserve(NumCommonArgs);
9537
9538 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009539 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009540
9541 // If the return value is not being used, the type may not be compatible
9542 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009543 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009544
9545 // Add the new return attributes.
9546 if (RAttrs)
9547 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009548
9549 AI = CS.arg_begin();
9550 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9551 const Type *ParamTy = FT->getParamType(i);
9552 if ((*AI)->getType() == ParamTy) {
9553 Args.push_back(*AI);
9554 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009555 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009556 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009557 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009558 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009559 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009560
9561 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009562 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009563 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009564 }
9565
9566 // If the function takes more arguments than the call was taking, add them
9567 // now...
9568 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9569 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9570
9571 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009572 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009573 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009574 cerr << "WARNING: While resolving call to function '"
9575 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009576 } else {
9577 // Add all of the arguments in their promoted form to the arg list...
9578 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9579 const Type *PTy = getPromotedType((*AI)->getType());
9580 if (PTy != (*AI)->getType()) {
9581 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009582 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9583 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009584 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009585 InsertNewInstBefore(Cast, *Caller);
9586 Args.push_back(Cast);
9587 } else {
9588 Args.push_back(*AI);
9589 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009590
Duncan Sandse1e520f2008-01-13 08:02:44 +00009591 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009592 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009593 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9594 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009595 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009596 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009597
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009598 if (NewRetTy == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009599 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009600
Chris Lattner58d74912008-03-12 17:45:29 +00009601 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009602
Chris Lattner9fe38862003-06-19 17:00:31 +00009603 Instruction *NC;
9604 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009605 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009606 Args.begin(), Args.end(),
9607 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009608 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009609 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009610 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009611 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9612 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009613 CallInst *CI = cast<CallInst>(Caller);
9614 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009615 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009616 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009617 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009618 }
9619
Chris Lattner6934a042007-02-11 01:23:03 +00009620 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009621 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009622 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009623 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009624 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009625 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009626 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009627
9628 // If this is an invoke instruction, we should insert it after the first
9629 // non-phi, instruction in the normal successor block.
9630 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +00009631 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +00009632 InsertNewInstBefore(NC, *I);
9633 } else {
9634 // Otherwise, it's a call, just insert cast right after the call instr
9635 InsertNewInstBefore(NC, *Caller);
9636 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009637 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009638 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009639 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009640 }
9641 }
9642
9643 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9644 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009645 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009646 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009647 return true;
9648}
9649
Duncan Sandscdb6d922007-09-17 10:26:40 +00009650// transformCallThroughTrampoline - Turn a call to a function created by the
9651// init_trampoline intrinsic into a direct call to the underlying function.
9652//
9653Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9654 Value *Callee = CS.getCalledValue();
9655 const PointerType *PTy = cast<PointerType>(Callee->getType());
9656 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009657 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009658
9659 // If the call already has the 'nest' attribute somewhere then give up -
9660 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009661 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009662 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009663
9664 IntrinsicInst *Tramp =
9665 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9666
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009667 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009668 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9669 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9670
Chris Lattner58d74912008-03-12 17:45:29 +00009671 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9672 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009673 unsigned NestIdx = 1;
9674 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009675 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009676
9677 // Look for a parameter marked with the 'nest' attribute.
9678 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9679 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009680 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009681 // Record the parameter type and any other attributes.
9682 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009683 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009684 break;
9685 }
9686
9687 if (NestTy) {
9688 Instruction *Caller = CS.getInstruction();
9689 std::vector<Value*> NewArgs;
9690 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9691
Chris Lattner58d74912008-03-12 17:45:29 +00009692 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9693 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009694
Duncan Sandscdb6d922007-09-17 10:26:40 +00009695 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009696 // mean appending it. Likewise for attributes.
9697
9698 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009699 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9700 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009701
Duncan Sandscdb6d922007-09-17 10:26:40 +00009702 {
9703 unsigned Idx = 1;
9704 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9705 do {
9706 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009707 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009708 Value *NestVal = Tramp->getOperand(3);
9709 if (NestVal->getType() != NestTy)
9710 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9711 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009712 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009713 }
9714
9715 if (I == E)
9716 break;
9717
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009718 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009719 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009720 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009721 NewAttrs.push_back
9722 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009723
9724 ++Idx, ++I;
9725 } while (1);
9726 }
9727
9728 // The trampoline may have been bitcast to a bogus type (FTy).
9729 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009730 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009731
Duncan Sandscdb6d922007-09-17 10:26:40 +00009732 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009733 NewTypes.reserve(FTy->getNumParams()+1);
9734
Duncan Sandscdb6d922007-09-17 10:26:40 +00009735 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009736 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009737 {
9738 unsigned Idx = 1;
9739 FunctionType::param_iterator I = FTy->param_begin(),
9740 E = FTy->param_end();
9741
9742 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009743 if (Idx == NestIdx)
9744 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009745 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009746
9747 if (I == E)
9748 break;
9749
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009750 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009751 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009752
9753 ++Idx, ++I;
9754 } while (1);
9755 }
9756
9757 // Replace the trampoline call with a direct call. Let the generic
9758 // code sort out any function type mismatches.
9759 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009760 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009761 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9762 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009763 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009764
9765 Instruction *NewCaller;
9766 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009767 NewCaller = InvokeInst::Create(NewCallee,
9768 II->getNormalDest(), II->getUnwindDest(),
9769 NewArgs.begin(), NewArgs.end(),
9770 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009771 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009772 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009773 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009774 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9775 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009776 if (cast<CallInst>(Caller)->isTailCall())
9777 cast<CallInst>(NewCaller)->setTailCall();
9778 cast<CallInst>(NewCaller)->
9779 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009780 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009781 }
9782 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9783 Caller->replaceAllUsesWith(NewCaller);
9784 Caller->eraseFromParent();
9785 RemoveFromWorkList(Caller);
9786 return 0;
9787 }
9788 }
9789
9790 // Replace the trampoline call with a direct call. Since there is no 'nest'
9791 // parameter, there is no need to adjust the argument list. Let the generic
9792 // code sort out any function type mismatches.
9793 Constant *NewCallee =
9794 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9795 CS.setCalledFunction(NewCallee);
9796 return CS.getInstruction();
9797}
9798
Chris Lattner7da52b22006-11-01 04:51:18 +00009799/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9800/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9801/// and a single binop.
9802Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9803 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009804 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9805 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009806 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009807 Value *LHSVal = FirstInst->getOperand(0);
9808 Value *RHSVal = FirstInst->getOperand(1);
9809
9810 const Type *LHSType = LHSVal->getType();
9811 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009812
9813 // Scan to see if all operands are the same opcode, all have one use, and all
9814 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009815 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009816 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009817 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009818 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009819 // types or GEP's with different index types.
9820 I->getOperand(0)->getType() != LHSType ||
9821 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009822 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009823
9824 // If they are CmpInst instructions, check their predicates
9825 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9826 if (cast<CmpInst>(I)->getPredicate() !=
9827 cast<CmpInst>(FirstInst)->getPredicate())
9828 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009829
9830 // Keep track of which operand needs a phi node.
9831 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9832 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009833 }
9834
Chris Lattner53738a42006-11-08 19:42:28 +00009835 // Otherwise, this is safe to transform, determine if it is profitable.
9836
9837 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9838 // Indexes are often folded into load/store instructions, so we don't want to
9839 // hide them behind a phi.
9840 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9841 return 0;
9842
Chris Lattner7da52b22006-11-01 04:51:18 +00009843 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009844 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009845 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009846 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009847 NewLHS = PHINode::Create(LHSType,
9848 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009849 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9850 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009851 InsertNewInstBefore(NewLHS, PN);
9852 LHSVal = NewLHS;
9853 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009854
9855 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009856 NewRHS = PHINode::Create(RHSType,
9857 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009858 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9859 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009860 InsertNewInstBefore(NewRHS, PN);
9861 RHSVal = NewRHS;
9862 }
9863
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009864 // Add all operands to the new PHIs.
9865 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9866 if (NewLHS) {
9867 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9868 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9869 }
9870 if (NewRHS) {
9871 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9872 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9873 }
9874 }
9875
Chris Lattner7da52b22006-11-01 04:51:18 +00009876 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009877 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009878 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009879 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009880 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009881 else {
9882 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009883 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009884 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009885}
9886
Chris Lattner76c73142006-11-01 07:13:54 +00009887/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9888/// of the block that defines it. This means that it must be obvious the value
9889/// of the load is not changed from the point of the load to the end of the
9890/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009891///
9892/// Finally, it is safe, but not profitable, to sink a load targetting a
9893/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9894/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009895static bool isSafeToSinkLoad(LoadInst *L) {
9896 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9897
9898 for (++BBI; BBI != E; ++BBI)
9899 if (BBI->mayWriteToMemory())
9900 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009901
9902 // Check for non-address taken alloca. If not address-taken already, it isn't
9903 // profitable to do this xform.
9904 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9905 bool isAddressTaken = false;
9906 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9907 UI != E; ++UI) {
9908 if (isa<LoadInst>(UI)) continue;
9909 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9910 // If storing TO the alloca, then the address isn't taken.
9911 if (SI->getOperand(1) == AI) continue;
9912 }
9913 isAddressTaken = true;
9914 break;
9915 }
9916
9917 if (!isAddressTaken)
9918 return false;
9919 }
9920
Chris Lattner76c73142006-11-01 07:13:54 +00009921 return true;
9922}
9923
Chris Lattner9fe38862003-06-19 17:00:31 +00009924
Chris Lattnerbac32862004-11-14 19:13:23 +00009925// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9926// operator and they all are only used by the PHI, PHI together their
9927// inputs, and do the operation once, to the result of the PHI.
9928Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9929 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9930
9931 // Scan the instruction, looking for input operations that can be folded away.
9932 // If all input operands to the phi are the same instruction (e.g. a cast from
9933 // the same type or "+42") we can pull the operation through the PHI, reducing
9934 // code size and simplifying code.
9935 Constant *ConstantOp = 0;
9936 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009937 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009938 if (isa<CastInst>(FirstInst)) {
9939 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009940 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009941 // Can fold binop, compare or shift here if the RHS is a constant,
9942 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009943 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009944 if (ConstantOp == 0)
9945 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009946 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9947 isVolatile = LI->isVolatile();
9948 // We can't sink the load if the loaded value could be modified between the
9949 // load and the PHI.
9950 if (LI->getParent() != PN.getIncomingBlock(0) ||
9951 !isSafeToSinkLoad(LI))
9952 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009953 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009954 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009955 return FoldPHIArgBinOpIntoPHI(PN);
9956 // Can't handle general GEPs yet.
9957 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009958 } else {
9959 return 0; // Cannot fold this operation.
9960 }
9961
9962 // Check to see if all arguments are the same operation.
9963 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9964 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9965 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009966 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009967 return 0;
9968 if (CastSrcTy) {
9969 if (I->getOperand(0)->getType() != CastSrcTy)
9970 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009971 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009972 // We can't sink the load if the loaded value could be modified between
9973 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009974 if (LI->isVolatile() != isVolatile ||
9975 LI->getParent() != PN.getIncomingBlock(i) ||
9976 !isSafeToSinkLoad(LI))
9977 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009978
9979 // If the PHI is volatile and its block has multiple successors, sinking
9980 // it would remove a load of the volatile value from the path through the
9981 // other successor.
9982 if (isVolatile &&
9983 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9984 return 0;
9985
9986
Chris Lattnerbac32862004-11-14 19:13:23 +00009987 } else if (I->getOperand(1) != ConstantOp) {
9988 return 0;
9989 }
9990 }
9991
9992 // Okay, they are all the same operation. Create a new PHI node of the
9993 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009994 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9995 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009996 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009997
9998 Value *InVal = FirstInst->getOperand(0);
9999 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010000
10001 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010002 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10003 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10004 if (NewInVal != InVal)
10005 InVal = 0;
10006 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10007 }
10008
10009 Value *PhiVal;
10010 if (InVal) {
10011 // The new PHI unions all of the same values together. This is really
10012 // common, so we handle it intelligently here for compile-time speed.
10013 PhiVal = InVal;
10014 delete NewPN;
10015 } else {
10016 InsertNewInstBefore(NewPN, PN);
10017 PhiVal = NewPN;
10018 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010019
Chris Lattnerbac32862004-11-14 19:13:23 +000010020 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010021 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010022 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010023 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010024 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010025 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010026 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010027 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010028 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10029
10030 // If this was a volatile load that we are merging, make sure to loop through
10031 // and mark all the input loads as non-volatile. If we don't do this, we will
10032 // insert a new volatile load and the old ones will not be deletable.
10033 if (isVolatile)
10034 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10035 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10036
10037 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010038}
Chris Lattnera1be5662002-05-02 17:06:02 +000010039
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010040/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10041/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010042static bool DeadPHICycle(PHINode *PN,
10043 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010044 if (PN->use_empty()) return true;
10045 if (!PN->hasOneUse()) return false;
10046
10047 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010048 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010049 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010050
10051 // Don't scan crazily complex things.
10052 if (PotentiallyDeadPHIs.size() == 16)
10053 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010054
10055 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10056 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010057
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010058 return false;
10059}
10060
Chris Lattnercf5008a2007-11-06 21:52:06 +000010061/// PHIsEqualValue - Return true if this phi node is always equal to
10062/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10063/// z = some value; x = phi (y, z); y = phi (x, z)
10064static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10065 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10066 // See if we already saw this PHI node.
10067 if (!ValueEqualPHIs.insert(PN))
10068 return true;
10069
10070 // Don't scan crazily complex things.
10071 if (ValueEqualPHIs.size() == 16)
10072 return false;
10073
10074 // Scan the operands to see if they are either phi nodes or are equal to
10075 // the value.
10076 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10077 Value *Op = PN->getIncomingValue(i);
10078 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10079 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10080 return false;
10081 } else if (Op != NonPhiInVal)
10082 return false;
10083 }
10084
10085 return true;
10086}
10087
10088
Chris Lattner473945d2002-05-06 18:06:38 +000010089// PHINode simplification
10090//
Chris Lattner7e708292002-06-25 16:13:24 +000010091Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010092 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010093 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010094
Owen Anderson7e057142006-07-10 22:03:18 +000010095 if (Value *V = PN.hasConstantValue())
10096 return ReplaceInstUsesWith(PN, V);
10097
Owen Anderson7e057142006-07-10 22:03:18 +000010098 // If all PHI operands are the same operation, pull them through the PHI,
10099 // reducing code size.
10100 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10101 PN.getIncomingValue(0)->hasOneUse())
10102 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10103 return Result;
10104
10105 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10106 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10107 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010108 if (PN.hasOneUse()) {
10109 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10110 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010111 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010112 PotentiallyDeadPHIs.insert(&PN);
10113 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10114 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10115 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010116
10117 // If this phi has a single use, and if that use just computes a value for
10118 // the next iteration of a loop, delete the phi. This occurs with unused
10119 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10120 // common case here is good because the only other things that catch this
10121 // are induction variable analysis (sometimes) and ADCE, which is only run
10122 // late.
10123 if (PHIUser->hasOneUse() &&
10124 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10125 PHIUser->use_back() == &PN) {
10126 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10127 }
10128 }
Owen Anderson7e057142006-07-10 22:03:18 +000010129
Chris Lattnercf5008a2007-11-06 21:52:06 +000010130 // We sometimes end up with phi cycles that non-obviously end up being the
10131 // same value, for example:
10132 // z = some value; x = phi (y, z); y = phi (x, z)
10133 // where the phi nodes don't necessarily need to be in the same block. Do a
10134 // quick check to see if the PHI node only contains a single non-phi value, if
10135 // so, scan to see if the phi cycle is actually equal to that value.
10136 {
10137 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10138 // Scan for the first non-phi operand.
10139 while (InValNo != NumOperandVals &&
10140 isa<PHINode>(PN.getIncomingValue(InValNo)))
10141 ++InValNo;
10142
10143 if (InValNo != NumOperandVals) {
10144 Value *NonPhiInVal = PN.getOperand(InValNo);
10145
10146 // Scan the rest of the operands to see if there are any conflicts, if so
10147 // there is no need to recursively scan other phis.
10148 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10149 Value *OpVal = PN.getIncomingValue(InValNo);
10150 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10151 break;
10152 }
10153
10154 // If we scanned over all operands, then we have one unique value plus
10155 // phi values. Scan PHI nodes to see if they all merge in each other or
10156 // the value.
10157 if (InValNo == NumOperandVals) {
10158 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10159 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10160 return ReplaceInstUsesWith(PN, NonPhiInVal);
10161 }
10162 }
10163 }
Chris Lattner60921c92003-12-19 05:58:40 +000010164 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010165}
10166
Reid Spencer17212df2006-12-12 09:18:51 +000010167static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10168 Instruction *InsertPoint,
10169 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010170 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10171 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010172 // We must cast correctly to the pointer type. Ensure that we
10173 // sign extend the integer value if it is smaller as this is
10174 // used for address computation.
10175 Instruction::CastOps opcode =
10176 (VTySize < PtrSize ? Instruction::SExt :
10177 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10178 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010179}
10180
Chris Lattnera1be5662002-05-02 17:06:02 +000010181
Chris Lattner7e708292002-06-25 16:13:24 +000010182Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010183 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010184 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010185 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010186 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010187 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010188
Chris Lattnere87597f2004-10-16 18:11:37 +000010189 if (isa<UndefValue>(GEP.getOperand(0)))
10190 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10191
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010192 bool HasZeroPointerIndex = false;
10193 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10194 HasZeroPointerIndex = C->isNullValue();
10195
10196 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010197 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010198
Chris Lattner28977af2004-04-05 01:30:19 +000010199 // Eliminate unneeded casts for indices.
10200 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010201
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010202 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010203 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010204 if (isa<SequentialType>(*GTI)) {
10205 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010206 if (CI->getOpcode() == Instruction::ZExt ||
10207 CI->getOpcode() == Instruction::SExt) {
10208 const Type *SrcTy = CI->getOperand(0)->getType();
10209 // We can eliminate a cast from i32 to i64 iff the target
10210 // is a 32-bit pointer target.
10211 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10212 MadeChange = true;
10213 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010214 }
10215 }
10216 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010217 // If we are using a wider index than needed for this platform, shrink it
10218 // to what we need. If the incoming value needs a cast instruction,
10219 // insert it. This explicit cast can make subsequent optimizations more
10220 // obvious.
10221 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010222 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010223 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010224 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010225 MadeChange = true;
10226 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010227 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10228 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010229 GEP.setOperand(i, Op);
10230 MadeChange = true;
10231 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010232 }
Chris Lattner28977af2004-04-05 01:30:19 +000010233 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010234 }
Chris Lattner28977af2004-04-05 01:30:19 +000010235 if (MadeChange) return &GEP;
10236
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010237 // If this GEP instruction doesn't move the pointer, and if the input operand
10238 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10239 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010240 if (GEP.hasAllZeroIndices()) {
10241 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10242 // If the bitcast is of an allocation, and the allocation will be
10243 // converted to match the type of the cast, don't touch this.
10244 if (isa<AllocationInst>(BCI->getOperand(0))) {
10245 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010246 if (Instruction *I = visitBitCast(*BCI)) {
10247 if (I != BCI) {
10248 I->takeName(BCI);
10249 BCI->getParent()->getInstList().insert(BCI, I);
10250 ReplaceInstUsesWith(*BCI, I);
10251 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010252 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010253 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010254 }
10255 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10256 }
10257 }
10258
Chris Lattner90ac28c2002-08-02 19:29:35 +000010259 // Combine Indices - If the source pointer to this getelementptr instruction
10260 // is a getelementptr instruction, combine the indices of the two
10261 // getelementptr instructions into a single instruction.
10262 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010263 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010264 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010265 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010266
10267 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010268 // Note that if our source is a gep chain itself that we wait for that
10269 // chain to be resolved before we perform this transformation. This
10270 // avoids us creating a TON of code in some cases.
10271 //
10272 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10273 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10274 return 0; // Wait until our source is folded to completion.
10275
Chris Lattner72588fc2007-02-15 22:48:32 +000010276 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010277
10278 // Find out whether the last index in the source GEP is a sequential idx.
10279 bool EndsWithSequential = false;
10280 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10281 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010282 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010283
Chris Lattner90ac28c2002-08-02 19:29:35 +000010284 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010285 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010286 // Replace: gep (gep %P, long B), long A, ...
10287 // With: T = long A+B; gep %P, T, ...
10288 //
Chris Lattner620ce142004-05-07 22:09:22 +000010289 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010290 if (SO1 == Constant::getNullValue(SO1->getType())) {
10291 Sum = GO1;
10292 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10293 Sum = SO1;
10294 } else {
10295 // If they aren't the same type, convert both to an integer of the
10296 // target's pointer size.
10297 if (SO1->getType() != GO1->getType()) {
10298 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010299 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010300 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010301 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010302 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010303 unsigned PS = TD->getPointerSizeInBits();
10304 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010305 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010306 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010307
Duncan Sands514ab342007-11-01 20:53:16 +000010308 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010309 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010310 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010311 } else {
10312 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010313 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10314 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010315 }
10316 }
10317 }
Chris Lattner620ce142004-05-07 22:09:22 +000010318 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10319 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10320 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010321 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010322 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010323 }
Chris Lattner28977af2004-04-05 01:30:19 +000010324 }
Chris Lattner620ce142004-05-07 22:09:22 +000010325
10326 // Recycle the GEP we already have if possible.
10327 if (SrcGEPOperands.size() == 2) {
10328 GEP.setOperand(0, SrcGEPOperands[0]);
10329 GEP.setOperand(1, Sum);
10330 return &GEP;
10331 } else {
10332 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10333 SrcGEPOperands.end()-1);
10334 Indices.push_back(Sum);
10335 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10336 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010337 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010338 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010339 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010340 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010341 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10342 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010343 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10344 }
10345
10346 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010347 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10348 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010349
Chris Lattner620ce142004-05-07 22:09:22 +000010350 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010351 // GEP of global variable. If all of the indices for this GEP are
10352 // constants, we can promote this to a constexpr instead of an instruction.
10353
10354 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010355 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010356 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10357 for (; I != E && isa<Constant>(*I); ++I)
10358 Indices.push_back(cast<Constant>(*I));
10359
10360 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010361 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10362 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010363
10364 // Replace all uses of the GEP with the new constexpr...
10365 return ReplaceInstUsesWith(GEP, CE);
10366 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010367 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010368 if (!isa<PointerType>(X->getType())) {
10369 // Not interesting. Source pointer must be a cast from pointer.
10370 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010371 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10372 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010373 //
10374 // This occurs when the program declares an array extern like "int X[];"
10375 //
10376 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10377 const PointerType *XTy = cast<PointerType>(X->getType());
10378 if (const ArrayType *XATy =
10379 dyn_cast<ArrayType>(XTy->getElementType()))
10380 if (const ArrayType *CATy =
10381 dyn_cast<ArrayType>(CPTy->getElementType()))
10382 if (CATy->getElementType() == XATy->getElementType()) {
10383 // At this point, we know that the cast source type is a pointer
10384 // to an array of the same type as the destination pointer
10385 // array. Because the array type is never stepped over (there
10386 // is a leading zero) we can fold the cast into this GEP.
10387 GEP.setOperand(0, X);
10388 return &GEP;
10389 }
10390 } else if (GEP.getNumOperands() == 2) {
10391 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010392 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10393 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010394 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10395 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10396 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010397 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10398 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010399 Value *Idx[2];
10400 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10401 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010402 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010403 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010404 // V and GEP are both pointer types --> BitCast
10405 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010406 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010407
10408 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010409 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010410 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010411 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010412
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010413 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010414 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010415 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010416
10417 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10418 // allow either a mul, shift, or constant here.
10419 Value *NewIdx = 0;
10420 ConstantInt *Scale = 0;
10421 if (ArrayEltSize == 1) {
10422 NewIdx = GEP.getOperand(1);
10423 Scale = ConstantInt::get(NewIdx->getType(), 1);
10424 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010425 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010426 Scale = CI;
10427 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10428 if (Inst->getOpcode() == Instruction::Shl &&
10429 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010430 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10431 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10432 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010433 NewIdx = Inst->getOperand(0);
10434 } else if (Inst->getOpcode() == Instruction::Mul &&
10435 isa<ConstantInt>(Inst->getOperand(1))) {
10436 Scale = cast<ConstantInt>(Inst->getOperand(1));
10437 NewIdx = Inst->getOperand(0);
10438 }
10439 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010440
Chris Lattner7835cdd2005-09-13 18:36:04 +000010441 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010442 // out, perform the transformation. Note, we don't know whether Scale is
10443 // signed or not. We'll use unsigned version of division/modulo
10444 // operation after making sure Scale doesn't have the sign bit set.
10445 if (Scale && Scale->getSExtValue() >= 0LL &&
10446 Scale->getZExtValue() % ArrayEltSize == 0) {
10447 Scale = ConstantInt::get(Scale->getType(),
10448 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010449 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010450 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010451 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010452 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010453 NewIdx = InsertNewInstBefore(Sc, GEP);
10454 }
10455
10456 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010457 Value *Idx[2];
10458 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10459 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010460 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010461 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010462 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10463 // The NewGEP must be pointer typed, so must the old one -> BitCast
10464 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010465 }
10466 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010467 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010468 }
10469
Chris Lattner8a2a3112001-12-14 16:52:21 +000010470 return 0;
10471}
10472
Chris Lattner0864acf2002-11-04 16:18:53 +000010473Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10474 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010475 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010476 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10477 const Type *NewTy =
10478 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010479 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010480
10481 // Create and insert the replacement instruction...
10482 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010483 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010484 else {
10485 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010486 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010487 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010488
10489 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010490
Chris Lattner0864acf2002-11-04 16:18:53 +000010491 // Scan to the end of the allocation instructions, to skip over a block of
10492 // allocas if possible...
10493 //
10494 BasicBlock::iterator It = New;
10495 while (isa<AllocationInst>(*It)) ++It;
10496
10497 // Now that I is pointing to the first non-allocation-inst in the block,
10498 // insert our getelementptr instruction...
10499 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010500 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010501 Value *Idx[2];
10502 Idx[0] = NullIdx;
10503 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010504 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10505 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010506
10507 // Now make everything use the getelementptr instead of the original
10508 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010509 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010510 } else if (isa<UndefValue>(AI.getArraySize())) {
10511 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010512 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010513 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010514
10515 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10516 // Note that we only do this for alloca's, because malloc should allocate and
10517 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010518 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010519 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010520 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10521
Chris Lattner0864acf2002-11-04 16:18:53 +000010522 return 0;
10523}
10524
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010525Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10526 Value *Op = FI.getOperand(0);
10527
Chris Lattner17be6352004-10-18 02:59:09 +000010528 // free undef -> unreachable.
10529 if (isa<UndefValue>(Op)) {
10530 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010531 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010532 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010533 return EraseInstFromFunction(FI);
10534 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010535
Chris Lattner6160e852004-02-28 04:57:37 +000010536 // If we have 'free null' delete the instruction. This can happen in stl code
10537 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010538 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010539 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010540
10541 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10542 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10543 FI.setOperand(0, CI->getOperand(0));
10544 return &FI;
10545 }
10546
10547 // Change free (gep X, 0,0,0,0) into free(X)
10548 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10549 if (GEPI->hasAllZeroIndices()) {
10550 AddToWorkList(GEPI);
10551 FI.setOperand(0, GEPI->getOperand(0));
10552 return &FI;
10553 }
10554 }
10555
10556 // Change free(malloc) into nothing, if the malloc has a single use.
10557 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10558 if (MI->hasOneUse()) {
10559 EraseInstFromFunction(FI);
10560 return EraseInstFromFunction(*MI);
10561 }
Chris Lattner6160e852004-02-28 04:57:37 +000010562
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010563 return 0;
10564}
10565
10566
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010567/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010568static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010569 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010570 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010571 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010572
Devang Patel99db6ad2007-10-18 19:52:32 +000010573 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10574 // Instead of loading constant c string, use corresponding integer value
10575 // directly if string length is small enough.
10576 const std::string &Str = CE->getOperand(0)->getStringValue();
10577 if (!Str.empty()) {
10578 unsigned len = Str.length();
10579 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10580 unsigned numBits = Ty->getPrimitiveSizeInBits();
10581 // Replace LI with immediate integer store.
10582 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010583 APInt StrVal(numBits, 0);
10584 APInt SingleChar(numBits, 0);
10585 if (TD->isLittleEndian()) {
10586 for (signed i = len-1; i >= 0; i--) {
10587 SingleChar = (uint64_t) Str[i];
10588 StrVal = (StrVal << 8) | SingleChar;
10589 }
10590 } else {
10591 for (unsigned i = 0; i < len; i++) {
10592 SingleChar = (uint64_t) Str[i];
10593 StrVal = (StrVal << 8) | SingleChar;
10594 }
10595 // Append NULL at the end.
10596 SingleChar = 0;
10597 StrVal = (StrVal << 8) | SingleChar;
10598 }
10599 Value *NL = ConstantInt::get(StrVal);
10600 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010601 }
10602 }
10603 }
10604
Chris Lattnerb89e0712004-07-13 01:49:43 +000010605 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010606 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010607 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010608
Reid Spencer42230162007-01-22 05:51:25 +000010609 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010610 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010611 // If the source is an array, the code below will not succeed. Check to
10612 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10613 // constants.
10614 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10615 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10616 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010617 Value *Idxs[2];
10618 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10619 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010620 SrcTy = cast<PointerType>(CastOp->getType());
10621 SrcPTy = SrcTy->getElementType();
10622 }
10623
Reid Spencer42230162007-01-22 05:51:25 +000010624 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010625 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010626 // Do not allow turning this into a load of an integer, which is then
10627 // casted to a pointer, this pessimizes pointer analysis a lot.
10628 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010629 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10630 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010631
Chris Lattnerf9527852005-01-31 04:50:46 +000010632 // Okay, we are casting from one integer or pointer type to another of
10633 // the same size. Instead of casting the pointer before the load, cast
10634 // the result of the loaded value.
10635 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10636 CI->getName(),
10637 LI.isVolatile()),LI);
10638 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010639 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010640 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010641 }
10642 }
10643 return 0;
10644}
10645
Chris Lattnerc10aced2004-09-19 18:43:46 +000010646/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010647/// from this value cannot trap. If it is not obviously safe to load from the
10648/// specified pointer, we do a quick local scan of the basic block containing
10649/// ScanFrom, to determine if the address is already accessed.
10650static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010651 // If it is an alloca it is always safe to load from.
10652 if (isa<AllocaInst>(V)) return true;
10653
Duncan Sands46318cd2007-09-19 10:25:38 +000010654 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010655 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010656 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010657 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010658
10659 // Otherwise, be a little bit agressive by scanning the local block where we
10660 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010661 // from/to. If so, the previous load or store would have already trapped,
10662 // so there is no harm doing an extra load (also, CSE will later eliminate
10663 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010664 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10665
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010666 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010667 --BBI;
10668
10669 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10670 if (LI->getOperand(0) == V) return true;
10671 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10672 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010673
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010674 }
Chris Lattner8a375202004-09-19 19:18:10 +000010675 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010676}
10677
Chris Lattner8d2e8882007-08-11 18:48:48 +000010678/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10679/// until we find the underlying object a pointer is referring to or something
10680/// we don't understand. Note that the returned pointer may be offset from the
10681/// input, because we ignore GEP indices.
10682static Value *GetUnderlyingObject(Value *Ptr) {
10683 while (1) {
10684 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10685 if (CE->getOpcode() == Instruction::BitCast ||
10686 CE->getOpcode() == Instruction::GetElementPtr)
10687 Ptr = CE->getOperand(0);
10688 else
10689 return Ptr;
10690 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10691 Ptr = BCI->getOperand(0);
10692 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10693 Ptr = GEP->getOperand(0);
10694 } else {
10695 return Ptr;
10696 }
10697 }
10698}
10699
Chris Lattner833b8a42003-06-26 05:06:25 +000010700Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10701 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010702
Dan Gohman9941f742007-07-20 16:34:21 +000010703 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010704 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10705 if (KnownAlign >
10706 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10707 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010708 LI.setAlignment(KnownAlign);
10709
Chris Lattner37366c12005-05-01 04:24:53 +000010710 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010711 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010712 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010713 return Res;
10714
10715 // None of the following transforms are legal for volatile loads.
10716 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010717
Chris Lattner62f254d2005-09-12 22:00:15 +000010718 if (&LI.getParent()->front() != &LI) {
10719 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010720 // If the instruction immediately before this is a store to the same
10721 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010722 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10723 if (SI->getOperand(1) == LI.getOperand(0))
10724 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010725 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10726 if (LIB->getOperand(0) == LI.getOperand(0))
10727 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010728 }
Chris Lattner37366c12005-05-01 04:24:53 +000010729
Christopher Lambb15147e2007-12-29 07:56:53 +000010730 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10731 const Value *GEPI0 = GEPI->getOperand(0);
10732 // TODO: Consider a target hook for valid address spaces for this xform.
10733 if (isa<ConstantPointerNull>(GEPI0) &&
10734 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010735 // Insert a new store to null instruction before the load to indicate
10736 // that this code is not reachable. We do this instead of inserting
10737 // an unreachable instruction directly because we cannot modify the
10738 // CFG.
10739 new StoreInst(UndefValue::get(LI.getType()),
10740 Constant::getNullValue(Op->getType()), &LI);
10741 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10742 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010743 }
Chris Lattner37366c12005-05-01 04:24:53 +000010744
Chris Lattnere87597f2004-10-16 18:11:37 +000010745 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010746 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010747 // TODO: Consider a target hook for valid address spaces for this xform.
10748 if (isa<UndefValue>(C) || (C->isNullValue() &&
10749 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010750 // Insert a new store to null instruction before the load to indicate that
10751 // this code is not reachable. We do this instead of inserting an
10752 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010753 new StoreInst(UndefValue::get(LI.getType()),
10754 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010755 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010756 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010757
Chris Lattnere87597f2004-10-16 18:11:37 +000010758 // Instcombine load (constant global) into the value loaded.
10759 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010760 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010761 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010762
Chris Lattnere87597f2004-10-16 18:11:37 +000010763 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010764 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010765 if (CE->getOpcode() == Instruction::GetElementPtr) {
10766 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010767 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010768 if (Constant *V =
10769 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010770 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010771 if (CE->getOperand(0)->isNullValue()) {
10772 // Insert a new store to null instruction before the load to indicate
10773 // that this code is not reachable. We do this instead of inserting
10774 // an unreachable instruction directly because we cannot modify the
10775 // CFG.
10776 new StoreInst(UndefValue::get(LI.getType()),
10777 Constant::getNullValue(Op->getType()), &LI);
10778 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10779 }
10780
Reid Spencer3da59db2006-11-27 01:05:10 +000010781 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010782 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010783 return Res;
10784 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010785 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010786 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010787
10788 // If this load comes from anywhere in a constant global, and if the global
10789 // is all undef or zero, we know what it loads.
10790 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10791 if (GV->isConstant() && GV->hasInitializer()) {
10792 if (GV->getInitializer()->isNullValue())
10793 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10794 else if (isa<UndefValue>(GV->getInitializer()))
10795 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10796 }
10797 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010798
Chris Lattner37366c12005-05-01 04:24:53 +000010799 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010800 // Change select and PHI nodes to select values instead of addresses: this
10801 // helps alias analysis out a lot, allows many others simplifications, and
10802 // exposes redundancy in the code.
10803 //
10804 // Note that we cannot do the transformation unless we know that the
10805 // introduced loads cannot trap! Something like this is valid as long as
10806 // the condition is always false: load (select bool %C, int* null, int* %G),
10807 // but it would not be valid if we transformed it to load from null
10808 // unconditionally.
10809 //
10810 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10811 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010812 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10813 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010814 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010815 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010816 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010817 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010818 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010819 }
10820
Chris Lattner684fe212004-09-23 15:46:00 +000010821 // load (select (cond, null, P)) -> load P
10822 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10823 if (C->isNullValue()) {
10824 LI.setOperand(0, SI->getOperand(2));
10825 return &LI;
10826 }
10827
10828 // load (select (cond, P, null)) -> load P
10829 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10830 if (C->isNullValue()) {
10831 LI.setOperand(0, SI->getOperand(1));
10832 return &LI;
10833 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010834 }
10835 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010836 return 0;
10837}
10838
Reid Spencer55af2b52007-01-19 21:20:31 +000010839/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010840/// when possible.
10841static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10842 User *CI = cast<User>(SI.getOperand(1));
10843 Value *CastOp = CI->getOperand(0);
10844
10845 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10846 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10847 const Type *SrcPTy = SrcTy->getElementType();
10848
Reid Spencer42230162007-01-22 05:51:25 +000010849 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010850 // If the source is an array, the code below will not succeed. Check to
10851 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10852 // constants.
10853 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10854 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10855 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010856 Value* Idxs[2];
10857 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10858 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010859 SrcTy = cast<PointerType>(CastOp->getType());
10860 SrcPTy = SrcTy->getElementType();
10861 }
10862
Reid Spencer67f827c2007-01-20 23:35:48 +000010863 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10864 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10865 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010866
10867 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010868 // the same size. Instead of casting the pointer before
10869 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010870 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010871 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010872 Instruction::CastOps opcode = Instruction::BitCast;
10873 const Type* CastSrcTy = SIOp0->getType();
10874 const Type* CastDstTy = SrcPTy;
10875 if (isa<PointerType>(CastDstTy)) {
10876 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010877 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010878 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010879 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010880 opcode = Instruction::PtrToInt;
10881 }
10882 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010883 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010884 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010885 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010886 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010887 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010888 return new StoreInst(NewCast, CastOp);
10889 }
10890 }
10891 }
10892 return 0;
10893}
10894
Chris Lattner2f503e62005-01-31 05:36:43 +000010895Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10896 Value *Val = SI.getOperand(0);
10897 Value *Ptr = SI.getOperand(1);
10898
10899 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010900 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010901 ++NumCombined;
10902 return 0;
10903 }
Chris Lattner836692d2007-01-15 06:51:56 +000010904
10905 // If the RHS is an alloca with a single use, zapify the store, making the
10906 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010907 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010908 if (isa<AllocaInst>(Ptr)) {
10909 EraseInstFromFunction(SI);
10910 ++NumCombined;
10911 return 0;
10912 }
10913
10914 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10915 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10916 GEP->getOperand(0)->hasOneUse()) {
10917 EraseInstFromFunction(SI);
10918 ++NumCombined;
10919 return 0;
10920 }
10921 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010922
Dan Gohman9941f742007-07-20 16:34:21 +000010923 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010924 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10925 if (KnownAlign >
10926 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10927 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010928 SI.setAlignment(KnownAlign);
10929
Chris Lattner9ca96412006-02-08 03:25:32 +000010930 // Do really simple DSE, to catch cases where there are several consequtive
10931 // stores to the same location, separated by a few arithmetic operations. This
10932 // situation often occurs with bitfield accesses.
10933 BasicBlock::iterator BBI = &SI;
10934 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10935 --ScanInsts) {
10936 --BBI;
10937
10938 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10939 // Prev store isn't volatile, and stores to the same location?
10940 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10941 ++NumDeadStore;
10942 ++BBI;
10943 EraseInstFromFunction(*PrevSI);
10944 continue;
10945 }
10946 break;
10947 }
10948
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010949 // If this is a load, we have to stop. However, if the loaded value is from
10950 // the pointer we're loading and is producing the pointer we're storing,
10951 // then *this* store is dead (X = load P; store X -> P).
10952 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010953 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010954 EraseInstFromFunction(SI);
10955 ++NumCombined;
10956 return 0;
10957 }
10958 // Otherwise, this is a load from some other location. Stores before it
10959 // may not be dead.
10960 break;
10961 }
10962
Chris Lattner9ca96412006-02-08 03:25:32 +000010963 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010964 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010965 break;
10966 }
10967
10968
10969 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010970
10971 // store X, null -> turns into 'unreachable' in SimplifyCFG
10972 if (isa<ConstantPointerNull>(Ptr)) {
10973 if (!isa<UndefValue>(Val)) {
10974 SI.setOperand(0, UndefValue::get(Val->getType()));
10975 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010976 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010977 ++NumCombined;
10978 }
10979 return 0; // Do not modify these!
10980 }
10981
10982 // store undef, Ptr -> noop
10983 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010984 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010985 ++NumCombined;
10986 return 0;
10987 }
10988
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010989 // If the pointer destination is a cast, see if we can fold the cast into the
10990 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010991 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010992 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10993 return Res;
10994 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010995 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010996 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10997 return Res;
10998
Chris Lattner408902b2005-09-12 23:23:25 +000010999
11000 // If this store is the last instruction in the basic block, and if the block
11001 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000011002 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000011003 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011004 if (BI->isUnconditional())
11005 if (SimplifyStoreAtEndOfBlock(SI))
11006 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011007
Chris Lattner2f503e62005-01-31 05:36:43 +000011008 return 0;
11009}
11010
Chris Lattner3284d1f2007-04-15 00:07:55 +000011011/// SimplifyStoreAtEndOfBlock - Turn things like:
11012/// if () { *P = v1; } else { *P = v2 }
11013/// into a phi node with a store in the successor.
11014///
Chris Lattner31755a02007-04-15 01:02:18 +000011015/// Simplify things like:
11016/// *P = v1; if () { *P = v2; }
11017/// into a phi node with a store in the successor.
11018///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011019bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11020 BasicBlock *StoreBB = SI.getParent();
11021
11022 // Check to see if the successor block has exactly two incoming edges. If
11023 // so, see if the other predecessor contains a store to the same location.
11024 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011025 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011026
11027 // Determine whether Dest has exactly two predecessors and, if so, compute
11028 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011029 pred_iterator PI = pred_begin(DestBB);
11030 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011031 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011032 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011033 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011034 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011035 return false;
11036
11037 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011038 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011039 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011040 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011041 }
Chris Lattner31755a02007-04-15 01:02:18 +000011042 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011043 return false;
11044
11045
Chris Lattner31755a02007-04-15 01:02:18 +000011046 // Verify that the other block ends in a branch and is not otherwise empty.
11047 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011048 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011049 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011050 return false;
11051
Chris Lattner31755a02007-04-15 01:02:18 +000011052 // If the other block ends in an unconditional branch, check for the 'if then
11053 // else' case. there is an instruction before the branch.
11054 StoreInst *OtherStore = 0;
11055 if (OtherBr->isUnconditional()) {
11056 // If this isn't a store, or isn't a store to the same location, bail out.
11057 --BBI;
11058 OtherStore = dyn_cast<StoreInst>(BBI);
11059 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11060 return false;
11061 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011062 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011063 // destinations is StoreBB, then we have the if/then case.
11064 if (OtherBr->getSuccessor(0) != StoreBB &&
11065 OtherBr->getSuccessor(1) != StoreBB)
11066 return false;
11067
11068 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011069 // if/then triangle. See if there is a store to the same ptr as SI that
11070 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011071 for (;; --BBI) {
11072 // Check to see if we find the matching store.
11073 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11074 if (OtherStore->getOperand(1) != SI.getOperand(1))
11075 return false;
11076 break;
11077 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011078 // If we find something that may be using the stored value, or if we run
11079 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011080 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11081 BBI == OtherBB->begin())
11082 return false;
11083 }
11084
11085 // In order to eliminate the store in OtherBr, we have to
11086 // make sure nothing reads the stored value in StoreBB.
11087 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11088 // FIXME: This should really be AA driven.
11089 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11090 return false;
11091 }
11092 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011093
Chris Lattner31755a02007-04-15 01:02:18 +000011094 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011095 Value *MergedVal = OtherStore->getOperand(0);
11096 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011097 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011098 PN->reserveOperandSpace(2);
11099 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011100 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11101 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011102 }
11103
11104 // Advance to a place where it is safe to insert the new store and
11105 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011106 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011107 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11108 OtherStore->isVolatile()), *BBI);
11109
11110 // Nuke the old stores.
11111 EraseInstFromFunction(SI);
11112 EraseInstFromFunction(*OtherStore);
11113 ++NumCombined;
11114 return true;
11115}
11116
Chris Lattner2f503e62005-01-31 05:36:43 +000011117
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011118Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11119 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011120 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011121 BasicBlock *TrueDest;
11122 BasicBlock *FalseDest;
11123 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11124 !isa<Constant>(X)) {
11125 // Swap Destinations and condition...
11126 BI.setCondition(X);
11127 BI.setSuccessor(0, FalseDest);
11128 BI.setSuccessor(1, TrueDest);
11129 return &BI;
11130 }
11131
Reid Spencere4d87aa2006-12-23 06:05:41 +000011132 // Cannonicalize fcmp_one -> fcmp_oeq
11133 FCmpInst::Predicate FPred; Value *Y;
11134 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11135 TrueDest, FalseDest)))
11136 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11137 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11138 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011139 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011140 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11141 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011142 // Swap Destinations and condition...
11143 BI.setCondition(NewSCC);
11144 BI.setSuccessor(0, FalseDest);
11145 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011146 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011147 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011148 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011149 return &BI;
11150 }
11151
11152 // Cannonicalize icmp_ne -> icmp_eq
11153 ICmpInst::Predicate IPred;
11154 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11155 TrueDest, FalseDest)))
11156 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11157 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11158 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11159 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011160 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011161 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11162 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011163 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011164 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011165 BI.setSuccessor(0, FalseDest);
11166 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011167 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011168 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011169 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011170 return &BI;
11171 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011172
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011173 return 0;
11174}
Chris Lattner0864acf2002-11-04 16:18:53 +000011175
Chris Lattner46238a62004-07-03 00:26:11 +000011176Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11177 Value *Cond = SI.getCondition();
11178 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11179 if (I->getOpcode() == Instruction::Add)
11180 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11181 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11182 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011183 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011184 AddRHS));
11185 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011186 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011187 return &SI;
11188 }
11189 }
11190 return 0;
11191}
11192
Chris Lattner220b0cf2006-03-05 00:22:33 +000011193/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11194/// is to leave as a vector operation.
11195static bool CheapToScalarize(Value *V, bool isConstant) {
11196 if (isa<ConstantAggregateZero>(V))
11197 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011198 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011199 if (isConstant) return true;
11200 // If all elts are the same, we can extract.
11201 Constant *Op0 = C->getOperand(0);
11202 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11203 if (C->getOperand(i) != Op0)
11204 return false;
11205 return true;
11206 }
11207 Instruction *I = dyn_cast<Instruction>(V);
11208 if (!I) return false;
11209
11210 // Insert element gets simplified to the inserted element or is deleted if
11211 // this is constant idx extract element and its a constant idx insertelt.
11212 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11213 isa<ConstantInt>(I->getOperand(2)))
11214 return true;
11215 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11216 return true;
11217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11218 if (BO->hasOneUse() &&
11219 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11220 CheapToScalarize(BO->getOperand(1), isConstant)))
11221 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011222 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11223 if (CI->hasOneUse() &&
11224 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11225 CheapToScalarize(CI->getOperand(1), isConstant)))
11226 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011227
11228 return false;
11229}
11230
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011231/// Read and decode a shufflevector mask.
11232///
11233/// It turns undef elements into values that are larger than the number of
11234/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011235static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11236 unsigned NElts = SVI->getType()->getNumElements();
11237 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11238 return std::vector<unsigned>(NElts, 0);
11239 if (isa<UndefValue>(SVI->getOperand(2)))
11240 return std::vector<unsigned>(NElts, 2*NElts);
11241
11242 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011243 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011244 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11245 if (isa<UndefValue>(CP->getOperand(i)))
11246 Result.push_back(NElts*2); // undef -> 8
11247 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011248 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011249 return Result;
11250}
11251
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011252/// FindScalarElement - Given a vector and an element number, see if the scalar
11253/// value is already around as a register, for example if it were inserted then
11254/// extracted from the vector.
11255static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011256 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11257 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011258 unsigned Width = PTy->getNumElements();
11259 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011260 return UndefValue::get(PTy->getElementType());
11261
11262 if (isa<UndefValue>(V))
11263 return UndefValue::get(PTy->getElementType());
11264 else if (isa<ConstantAggregateZero>(V))
11265 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011266 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011267 return CP->getOperand(EltNo);
11268 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11269 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011270 if (!isa<ConstantInt>(III->getOperand(2)))
11271 return 0;
11272 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011273
11274 // If this is an insert to the element we are looking for, return the
11275 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011276 if (EltNo == IIElt)
11277 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011278
11279 // Otherwise, the insertelement doesn't modify the value, recurse on its
11280 // vector input.
11281 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011282 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011283 unsigned InEl = getShuffleMask(SVI)[EltNo];
11284 if (InEl < Width)
11285 return FindScalarElement(SVI->getOperand(0), InEl);
11286 else if (InEl < Width*2)
11287 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11288 else
11289 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011290 }
11291
11292 // Otherwise, we don't know.
11293 return 0;
11294}
11295
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011296Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011297
Dan Gohman07a96762007-07-16 14:29:03 +000011298 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011299 if (isa<UndefValue>(EI.getOperand(0)))
11300 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11301
Dan Gohman07a96762007-07-16 14:29:03 +000011302 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011303 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11304 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11305
Reid Spencer9d6565a2007-02-15 02:26:10 +000011306 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011307 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011308 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011309 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011310 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011311 if (C->getOperand(i) != op0) {
11312 op0 = 0;
11313 break;
11314 }
11315 if (op0)
11316 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011317 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011318
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011319 // If extracting a specified index from the vector, see if we can recursively
11320 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011321 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011322 unsigned IndexVal = IdxC->getZExtValue();
11323 unsigned VectorWidth =
11324 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11325
11326 // If this is extracting an invalid index, turn this into undef, to avoid
11327 // crashing the code below.
11328 if (IndexVal >= VectorWidth)
11329 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11330
Chris Lattner867b99f2006-10-05 06:55:50 +000011331 // This instruction only demands the single element from the input vector.
11332 // If the input vector has a single use, simplify it based on this use
11333 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011334 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011335 uint64_t UndefElts;
11336 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011337 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011338 UndefElts)) {
11339 EI.setOperand(0, V);
11340 return &EI;
11341 }
11342 }
11343
Reid Spencerb83eb642006-10-20 07:07:24 +000011344 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011345 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011346
11347 // If the this extractelement is directly using a bitcast from a vector of
11348 // the same number of elements, see if we can find the source element from
11349 // it. In this case, we will end up needing to bitcast the scalars.
11350 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11351 if (const VectorType *VT =
11352 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11353 if (VT->getNumElements() == VectorWidth)
11354 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11355 return new BitCastInst(Elt, EI.getType());
11356 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011357 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011358
Chris Lattner73fa49d2006-05-25 22:53:38 +000011359 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011360 if (I->hasOneUse()) {
11361 // Push extractelement into predecessor operation if legal and
11362 // profitable to do so
11363 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011364 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11365 if (CheapToScalarize(BO, isConstantElt)) {
11366 ExtractElementInst *newEI0 =
11367 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11368 EI.getName()+".lhs");
11369 ExtractElementInst *newEI1 =
11370 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11371 EI.getName()+".rhs");
11372 InsertNewInstBefore(newEI0, EI);
11373 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011374 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011375 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011376 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011377 unsigned AS =
11378 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011379 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11380 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011381 GetElementPtrInst *GEP =
11382 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011383 InsertNewInstBefore(GEP, EI);
11384 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011385 }
11386 }
11387 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11388 // Extracting the inserted element?
11389 if (IE->getOperand(2) == EI.getOperand(1))
11390 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11391 // If the inserted and extracted elements are constants, they must not
11392 // be the same value, extract from the pre-inserted value instead.
11393 if (isa<Constant>(IE->getOperand(2)) &&
11394 isa<Constant>(EI.getOperand(1))) {
11395 AddUsesToWorkList(EI);
11396 EI.setOperand(0, IE->getOperand(0));
11397 return &EI;
11398 }
11399 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11400 // If this is extracting an element from a shufflevector, figure out where
11401 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011402 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11403 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011404 Value *Src;
11405 if (SrcIdx < SVI->getType()->getNumElements())
11406 Src = SVI->getOperand(0);
11407 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11408 SrcIdx -= SVI->getType()->getNumElements();
11409 Src = SVI->getOperand(1);
11410 } else {
11411 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011412 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011413 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011414 }
11415 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011416 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011417 return 0;
11418}
11419
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011420/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11421/// elements from either LHS or RHS, return the shuffle mask and true.
11422/// Otherwise, return false.
11423static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11424 std::vector<Constant*> &Mask) {
11425 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11426 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011427 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011428
11429 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011430 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011431 return true;
11432 } else if (V == LHS) {
11433 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011434 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011435 return true;
11436 } else if (V == RHS) {
11437 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011438 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011439 return true;
11440 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11441 // If this is an insert of an extract from some other vector, include it.
11442 Value *VecOp = IEI->getOperand(0);
11443 Value *ScalarOp = IEI->getOperand(1);
11444 Value *IdxOp = IEI->getOperand(2);
11445
Chris Lattnerd929f062006-04-27 21:14:21 +000011446 if (!isa<ConstantInt>(IdxOp))
11447 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011448 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011449
11450 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11451 // Okay, we can handle this if the vector we are insertinting into is
11452 // transitively ok.
11453 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11454 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011455 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011456 return true;
11457 }
11458 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11459 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011460 EI->getOperand(0)->getType() == V->getType()) {
11461 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011462 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011463
11464 // This must be extracting from either LHS or RHS.
11465 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11466 // Okay, we can handle this if the vector we are insertinting into is
11467 // transitively ok.
11468 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11469 // If so, update the mask to reflect the inserted value.
11470 if (EI->getOperand(0) == LHS) {
11471 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011472 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011473 } else {
11474 assert(EI->getOperand(0) == RHS);
11475 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011476 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011477
11478 }
11479 return true;
11480 }
11481 }
11482 }
11483 }
11484 }
11485 // TODO: Handle shufflevector here!
11486
11487 return false;
11488}
11489
11490/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11491/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11492/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011493static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011494 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011495 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011496 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011497 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011498 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011499
11500 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011501 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011502 return V;
11503 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011504 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011505 return V;
11506 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11507 // If this is an insert of an extract from some other vector, include it.
11508 Value *VecOp = IEI->getOperand(0);
11509 Value *ScalarOp = IEI->getOperand(1);
11510 Value *IdxOp = IEI->getOperand(2);
11511
11512 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11513 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11514 EI->getOperand(0)->getType() == V->getType()) {
11515 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011516 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11517 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011518
11519 // Either the extracted from or inserted into vector must be RHSVec,
11520 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011521 if (EI->getOperand(0) == RHS || RHS == 0) {
11522 RHS = EI->getOperand(0);
11523 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011524 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011525 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011526 return V;
11527 }
11528
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011529 if (VecOp == RHS) {
11530 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011531 // Everything but the extracted element is replaced with the RHS.
11532 for (unsigned i = 0; i != NumElts; ++i) {
11533 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011534 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011535 }
11536 return V;
11537 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011538
11539 // If this insertelement is a chain that comes from exactly these two
11540 // vectors, return the vector and the effective shuffle.
11541 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11542 return EI->getOperand(0);
11543
Chris Lattnerefb47352006-04-15 01:39:45 +000011544 }
11545 }
11546 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011547 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011548
11549 // Otherwise, can't do anything fancy. Return an identity vector.
11550 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011551 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011552 return V;
11553}
11554
11555Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11556 Value *VecOp = IE.getOperand(0);
11557 Value *ScalarOp = IE.getOperand(1);
11558 Value *IdxOp = IE.getOperand(2);
11559
Chris Lattner599ded12007-04-09 01:11:16 +000011560 // Inserting an undef or into an undefined place, remove this.
11561 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11562 ReplaceInstUsesWith(IE, VecOp);
11563
Chris Lattnerefb47352006-04-15 01:39:45 +000011564 // If the inserted element was extracted from some other vector, and if the
11565 // indexes are constant, try to turn this into a shufflevector operation.
11566 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11567 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11568 EI->getOperand(0)->getType() == IE.getType()) {
11569 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011570 unsigned ExtractedIdx =
11571 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011572 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011573
11574 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11575 return ReplaceInstUsesWith(IE, VecOp);
11576
11577 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11578 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11579
11580 // If we are extracting a value from a vector, then inserting it right
11581 // back into the same place, just use the input vector.
11582 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11583 return ReplaceInstUsesWith(IE, VecOp);
11584
11585 // We could theoretically do this for ANY input. However, doing so could
11586 // turn chains of insertelement instructions into a chain of shufflevector
11587 // instructions, and right now we do not merge shufflevectors. As such,
11588 // only do this in a situation where it is clear that there is benefit.
11589 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11590 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11591 // the values of VecOp, except then one read from EIOp0.
11592 // Build a new shuffle mask.
11593 std::vector<Constant*> Mask;
11594 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011595 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011596 else {
11597 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011598 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011599 NumVectorElts));
11600 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011601 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011602 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011603 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011604 }
11605
11606 // If this insertelement isn't used by some other insertelement, turn it
11607 // (and any insertelements it points to), into one big shuffle.
11608 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11609 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011610 Value *RHS = 0;
11611 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11612 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11613 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011614 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011615 }
11616 }
11617 }
11618
11619 return 0;
11620}
11621
11622
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011623Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11624 Value *LHS = SVI.getOperand(0);
11625 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011626 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011627
11628 bool MadeChange = false;
11629
Chris Lattner867b99f2006-10-05 06:55:50 +000011630 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011631 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011632 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11633
Chris Lattnere4929dd2007-01-05 07:36:08 +000011634 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011635 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011636 if (isa<UndefValue>(SVI.getOperand(1))) {
11637 // Scan to see if there are any references to the RHS. If so, replace them
11638 // with undef element refs and set MadeChange to true.
11639 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11640 if (Mask[i] >= e && Mask[i] != 2*e) {
11641 Mask[i] = 2*e;
11642 MadeChange = true;
11643 }
11644 }
11645
11646 if (MadeChange) {
11647 // Remap any references to RHS to use LHS.
11648 std::vector<Constant*> Elts;
11649 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11650 if (Mask[i] == 2*e)
11651 Elts.push_back(UndefValue::get(Type::Int32Ty));
11652 else
11653 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11654 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011655 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011656 }
11657 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011658
Chris Lattner863bcff2006-05-25 23:48:38 +000011659 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11660 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11661 if (LHS == RHS || isa<UndefValue>(LHS)) {
11662 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011663 // shuffle(undef,undef,mask) -> undef.
11664 return ReplaceInstUsesWith(SVI, LHS);
11665 }
11666
Chris Lattner863bcff2006-05-25 23:48:38 +000011667 // Remap any references to RHS to use LHS.
11668 std::vector<Constant*> Elts;
11669 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011670 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011671 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011672 else {
11673 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11674 (Mask[i] < e && isa<UndefValue>(LHS)))
11675 Mask[i] = 2*e; // Turn into undef.
11676 else
11677 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011678 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011679 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011680 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011681 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011682 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011683 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011684 LHS = SVI.getOperand(0);
11685 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011686 MadeChange = true;
11687 }
11688
Chris Lattner7b2e27922006-05-26 00:29:06 +000011689 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011690 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011691
Chris Lattner863bcff2006-05-25 23:48:38 +000011692 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11693 if (Mask[i] >= e*2) continue; // Ignore undef values.
11694 // Is this an identity shuffle of the LHS value?
11695 isLHSID &= (Mask[i] == i);
11696
11697 // Is this an identity shuffle of the RHS value?
11698 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011699 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011700
Chris Lattner863bcff2006-05-25 23:48:38 +000011701 // Eliminate identity shuffles.
11702 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11703 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011704
Chris Lattner7b2e27922006-05-26 00:29:06 +000011705 // If the LHS is a shufflevector itself, see if we can combine it with this
11706 // one without producing an unusual shuffle. Here we are really conservative:
11707 // we are absolutely afraid of producing a shuffle mask not in the input
11708 // program, because the code gen may not be smart enough to turn a merged
11709 // shuffle into two specific shuffles: it may produce worse code. As such,
11710 // we only merge two shuffles if the result is one of the two input shuffle
11711 // masks. In this case, merging the shuffles just removes one instruction,
11712 // which we know is safe. This is good for things like turning:
11713 // (splat(splat)) -> splat.
11714 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11715 if (isa<UndefValue>(RHS)) {
11716 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11717
11718 std::vector<unsigned> NewMask;
11719 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11720 if (Mask[i] >= 2*e)
11721 NewMask.push_back(2*e);
11722 else
11723 NewMask.push_back(LHSMask[Mask[i]]);
11724
11725 // If the result mask is equal to the src shuffle or this shuffle mask, do
11726 // the replacement.
11727 if (NewMask == LHSMask || NewMask == Mask) {
11728 std::vector<Constant*> Elts;
11729 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11730 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011731 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011732 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011733 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011734 }
11735 }
11736 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11737 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011738 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011739 }
11740 }
11741 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011742
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011743 return MadeChange ? &SVI : 0;
11744}
11745
11746
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011747
Chris Lattnerea1c4542004-12-08 23:43:58 +000011748
11749/// TryToSinkInstruction - Try to move the specified instruction from its
11750/// current block into the beginning of DestBlock, which can only happen if it's
11751/// safe to move the instruction past all of the instructions between it and the
11752/// end of its block.
11753static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11754 assert(I->hasOneUse() && "Invariants didn't hold!");
11755
Chris Lattner108e9022005-10-27 17:13:11 +000011756 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011757 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11758 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011759
Chris Lattnerea1c4542004-12-08 23:43:58 +000011760 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011761 if (isa<AllocaInst>(I) && I->getParent() ==
11762 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011763 return false;
11764
Chris Lattner96a52a62004-12-09 07:14:34 +000011765 // We can only sink load instructions if there is nothing between the load and
11766 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011767 if (I->mayReadFromMemory()) {
11768 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011769 Scan != E; ++Scan)
11770 if (Scan->mayWriteToMemory())
11771 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011772 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011773
Dan Gohman02dea8b2008-05-23 21:05:58 +000011774 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000011775
Chris Lattner4bc5f802005-08-08 19:11:57 +000011776 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011777 ++NumSunkInst;
11778 return true;
11779}
11780
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011781
11782/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11783/// all reachable code to the worklist.
11784///
11785/// This has a couple of tricks to make the code faster and more powerful. In
11786/// particular, we constant fold and DCE instructions as we go, to avoid adding
11787/// them to the worklist (this significantly speeds up instcombine on code where
11788/// many instructions are dead or constant). Additionally, if we find a branch
11789/// whose condition is a known constant, we only visit the reachable successors.
11790///
11791static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011792 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011793 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011794 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011795 std::vector<BasicBlock*> Worklist;
11796 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011797
Chris Lattner2c7718a2007-03-23 19:17:18 +000011798 while (!Worklist.empty()) {
11799 BB = Worklist.back();
11800 Worklist.pop_back();
11801
11802 // We have now visited this block! If we've already been here, ignore it.
11803 if (!Visited.insert(BB)) continue;
11804
11805 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11806 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011807
Chris Lattner2c7718a2007-03-23 19:17:18 +000011808 // DCE instruction if trivially dead.
11809 if (isInstructionTriviallyDead(Inst)) {
11810 ++NumDeadInst;
11811 DOUT << "IC: DCE: " << *Inst;
11812 Inst->eraseFromParent();
11813 continue;
11814 }
11815
11816 // ConstantProp instruction if trivially constant.
11817 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11818 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11819 Inst->replaceAllUsesWith(C);
11820 ++NumConstProp;
11821 Inst->eraseFromParent();
11822 continue;
11823 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011824
Chris Lattner2c7718a2007-03-23 19:17:18 +000011825 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011826 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011827
11828 // Recursively visit successors. If this is a branch or switch on a
11829 // constant, only visit the reachable successor.
11830 TerminatorInst *TI = BB->getTerminator();
11831 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11832 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11833 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011834 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011835 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011836 continue;
11837 }
11838 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11839 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11840 // See if this is an explicit destination.
11841 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11842 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011843 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011844 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011845 continue;
11846 }
11847
11848 // Otherwise it is the default destination.
11849 Worklist.push_back(SI->getSuccessor(0));
11850 continue;
11851 }
11852 }
11853
11854 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11855 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011856 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011857}
11858
Chris Lattnerec9c3582007-03-03 02:04:50 +000011859bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011860 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011861 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011862
11863 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11864 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011865
Chris Lattnerb3d59702005-07-07 20:40:38 +000011866 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011867 // Do a depth-first traversal of the function, populate the worklist with
11868 // the reachable instructions. Ignore blocks that are not reachable. Keep
11869 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011870 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011871 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011872
Chris Lattnerb3d59702005-07-07 20:40:38 +000011873 // Do a quick scan over the function. If we find any blocks that are
11874 // unreachable, remove any instructions inside of them. This prevents
11875 // the instcombine code from having to deal with some bad special cases.
11876 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11877 if (!Visited.count(BB)) {
11878 Instruction *Term = BB->getTerminator();
11879 while (Term != BB->begin()) { // Remove instrs bottom-up
11880 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011881
Bill Wendlingb7427032006-11-26 09:46:52 +000011882 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011883 ++NumDeadInst;
11884
11885 if (!I->use_empty())
11886 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11887 I->eraseFromParent();
11888 }
11889 }
11890 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011891
Chris Lattnerdbab3862007-03-02 21:28:56 +000011892 while (!Worklist.empty()) {
11893 Instruction *I = RemoveOneFromWorkList();
11894 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011895
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011896 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011897 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011898 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011899 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011900 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011901 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011902
Bill Wendlingb7427032006-11-26 09:46:52 +000011903 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011904
11905 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011906 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011907 continue;
11908 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011909
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011910 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011911 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011912 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011913
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011914 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011915 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011916 ReplaceInstUsesWith(*I, C);
11917
Chris Lattner62b14df2002-09-02 04:59:56 +000011918 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011919 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011920 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011921 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011922 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011923
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000011924 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11925 // See if we can constant fold its operands.
11926 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11927 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11928 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11929 i->set(NewC);
11930 }
11931 }
11932 }
11933
Chris Lattnerea1c4542004-12-08 23:43:58 +000011934 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011935 // FIXME: Remove GetResultInst test when first class support for aggregates
11936 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011937 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011938 BasicBlock *BB = I->getParent();
11939 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11940 if (UserParent != BB) {
11941 bool UserIsSuccessor = false;
11942 // See if the user is one of our successors.
11943 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11944 if (*SI == UserParent) {
11945 UserIsSuccessor = true;
11946 break;
11947 }
11948
11949 // If the user is one of our immediate successors, and if that successor
11950 // only has us as a predecessors (we'd have to split the critical edge
11951 // otherwise), we can keep going.
11952 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11953 next(pred_begin(UserParent)) == pred_end(UserParent))
11954 // Okay, the CFG is simple enough, try to sink this instruction.
11955 Changed |= TryToSinkInstruction(I, UserParent);
11956 }
11957 }
11958
Chris Lattner8a2a3112001-12-14 16:52:21 +000011959 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011960#ifndef NDEBUG
11961 std::string OrigI;
11962#endif
11963 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011964 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011965 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011966 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011967 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011968 DOUT << "IC: Old = " << *I
11969 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011970
Chris Lattnerf523d062004-06-09 05:08:07 +000011971 // Everything uses the new instruction now.
11972 I->replaceAllUsesWith(Result);
11973
11974 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011975 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011976 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011977
Chris Lattner6934a042007-02-11 01:23:03 +000011978 // Move the name to the new instruction first.
11979 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011980
11981 // Insert the new instruction into the basic block...
11982 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011983 BasicBlock::iterator InsertPos = I;
11984
11985 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11986 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11987 ++InsertPos;
11988
11989 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011990
Chris Lattner00d51312004-05-01 23:27:23 +000011991 // Make sure that we reprocess all operands now that we reduced their
11992 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011993 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011994
Chris Lattnerf523d062004-06-09 05:08:07 +000011995 // Instructions can end up on the worklist more than once. Make sure
11996 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011997 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011998
11999 // Erase the old instruction.
12000 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000012001 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012002#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000012003 DOUT << "IC: Mod = " << OrigI
12004 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000012005#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012006
Chris Lattner90ac28c2002-08-02 19:29:35 +000012007 // If the instruction was modified, it's possible that it is now dead.
12008 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012009 if (isInstructionTriviallyDead(I)) {
12010 // Make sure we process all operands now that we are reducing their
12011 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000012012 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012013
Chris Lattner00d51312004-05-01 23:27:23 +000012014 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012015 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000012016 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000012017 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000012018 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000012019 AddToWorkList(I);
12020 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012021 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012022 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012023 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012024 }
12025 }
12026
Chris Lattnerec9c3582007-03-03 02:04:50 +000012027 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012028
12029 // Do an explicit clear, this shrinks the map if needed.
12030 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012031 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012032}
12033
Chris Lattnerec9c3582007-03-03 02:04:50 +000012034
12035bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012036 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12037
Chris Lattnerec9c3582007-03-03 02:04:50 +000012038 bool EverMadeChange = false;
12039
12040 // Iterate while there is work to do.
12041 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012042 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012043 EverMadeChange = true;
12044 return EverMadeChange;
12045}
12046
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012047FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012048 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012049}
Brian Gaeked0fde302003-11-11 22:41:34 +000012050