blob: 084f874f921fb6f6bf00b90adb560edf4e708d8e [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);
Chris Lattner8d969642003-03-10 23:06:50 +0000553 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000554}
555
Chris Lattner8d969642003-03-10 23:06:50 +0000556static inline Value *dyn_castNotVal(Value *V) {
557 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000558 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000559
560 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000562 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000563 return 0;
564}
565
Chris Lattnerc8802d22003-03-11 00:12:48 +0000566// dyn_castFoldableMul - If this value is a multiply that can be folded into
567// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000568// non-constant operand of the multiply, and set CST to point to the multiplier.
569// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570//
Chris Lattner50af16a2004-11-13 19:50:12 +0000571static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000572 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000573 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000574 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000575 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000576 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000577 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000578 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000579 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000580 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000581 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000582 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000583 return I->getOperand(0);
584 }
585 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000586 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000587}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000588
Chris Lattner574da9b2005-01-13 20:14:25 +0000589/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
590/// expression, return it.
591static User *dyn_castGetElementPtr(Value *V) {
592 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
593 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
594 if (CE->getOpcode() == Instruction::GetElementPtr)
595 return cast<User>(V);
596 return false;
597}
598
Dan Gohmaneee962e2008-04-10 18:43:06 +0000599/// getOpcode - If this is an Instruction or a ConstantExpr, return the
600/// opcode value. Otherwise return UserOp1.
Dan Gohman45b4e482008-05-19 22:14:15 +0000601static unsigned getOpcode(Value *V) {
602 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000603 return I->getOpcode();
Dan Gohman45b4e482008-05-19 22:14:15 +0000604 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000605 return CE->getOpcode();
606 // Use UserOp1 to mean there's no opcode.
607 return Instruction::UserOp1;
608}
609
Reid Spencer7177c3a2007-03-25 05:33:51 +0000610/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000611static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000612 APInt Val(C->getValue());
613 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000614}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000616static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000617 APInt Val(C->getValue());
618 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000619}
620/// Add - Add two ConstantInts together
621static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
622 return ConstantInt::get(C1->getValue() + C2->getValue());
623}
624/// And - Bitwise AND two ConstantInts together
625static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
626 return ConstantInt::get(C1->getValue() & C2->getValue());
627}
628/// Subtract - Subtract one ConstantInt from another
629static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
630 return ConstantInt::get(C1->getValue() - C2->getValue());
631}
632/// Multiply - Multiply two ConstantInts together
633static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
634 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000635}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000636/// MultiplyOverflows - True if the multiply can not be expressed in an int
637/// this size.
638static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
639 uint32_t W = C1->getBitWidth();
640 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
641 if (sign) {
642 LHSExt.sext(W * 2);
643 RHSExt.sext(W * 2);
644 } else {
645 LHSExt.zext(W * 2);
646 RHSExt.zext(W * 2);
647 }
648
649 APInt MulExt = LHSExt * RHSExt;
650
651 if (sign) {
652 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
653 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
654 return MulExt.slt(Min) || MulExt.sgt(Max);
655 } else
656 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
657}
Chris Lattner955f3312004-09-28 21:48:02 +0000658
Chris Lattner68d5ff22006-02-09 07:38:58 +0000659/// ComputeMaskedBits - Determine which of the bits specified in Mask are
660/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000661/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
662/// processing.
663/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
664/// we cannot optimize based on the assumption that it is zero without changing
665/// it to be an explicit zero. If we don't change it to zero, other code could
666/// optimized based on the contradictory assumption that it is non-zero.
667/// Because instcombine aggressively folds operations with undef args anyway,
668/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000669void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
670 APInt& KnownZero, APInt& KnownOne,
Dan Gohman45b4e482008-05-19 22:14:15 +0000671 unsigned Depth) const {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000672 assert(V && "No Value?");
673 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000674 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000675 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
676 "Not integer or pointer type!");
677 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
678 (!isa<IntegerType>(V->getType()) ||
679 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000680 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000681 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000682 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman45b4e482008-05-19 22:14:15 +0000683
Reid Spencer3e7594f2007-03-08 01:46:38 +0000684 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
685 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000686 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000687 KnownZero = ~KnownOne & Mask;
688 return;
689 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000690 // Null is all-zeros.
691 if (isa<ConstantPointerNull>(V)) {
692 KnownOne.clear();
693 KnownZero = Mask;
694 return;
695 }
696 // The address of an aligned GlobalValue has trailing zeros.
697 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
698 unsigned Align = GV->getAlignment();
699 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
700 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
701 if (Align > 0)
702 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
703 CountTrailingZeros_32(Align));
704 else
705 KnownZero.clear();
706 KnownOne.clear();
707 return;
708 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000709
Dan Gohman23e8b712008-04-28 17:02:21 +0000710 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
711
Reid Spencer3e7594f2007-03-08 01:46:38 +0000712 if (Depth == 6 || Mask == 0)
713 return; // Limit search depth.
714
Dan Gohmaneee962e2008-04-10 18:43:06 +0000715 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000716 if (!I) return;
717
718 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000719 switch (getOpcode(I)) {
720 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000721 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000722 // If either the LHS or the RHS are Zero, the result is zero.
723 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000724 APInt Mask2(Mask & ~KnownZero);
725 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000726 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
727 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
728
729 // Output known-1 bits are only known if set in both the LHS & RHS.
730 KnownOne &= KnownOne2;
731 // Output known-0 are known to be clear if zero in either the LHS | RHS.
732 KnownZero |= KnownZero2;
733 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000734 }
735 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000736 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000737 APInt Mask2(Mask & ~KnownOne);
738 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000739 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
740 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
741
742 // Output known-0 bits are only known if clear in both the LHS & RHS.
743 KnownZero &= KnownZero2;
744 // Output known-1 are known to be set if set in either the LHS | RHS.
745 KnownOne |= KnownOne2;
746 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000747 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000748 case Instruction::Xor: {
749 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
750 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
753
754 // Output known-0 bits are known if clear or set in both the LHS & RHS.
755 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
756 // Output known-1 are known to be set if set in only one of the LHS, RHS.
757 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
758 KnownZero = KnownZeroOut;
759 return;
760 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000761 case Instruction::Mul: {
762 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
763 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
764 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
765 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
766 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
767
768 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000769 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000770 // More trickiness is possible, but this is sufficient for the
771 // interesting case of alignment computation.
772 KnownOne.clear();
773 unsigned TrailZ = KnownZero.countTrailingOnes() +
774 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000775 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000776 KnownZero2.countLeadingOnes(),
777 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000778
Dan Gohmaneee962e2008-04-10 18:43:06 +0000779 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000780 LeadZ = std::min(LeadZ, BitWidth);
781 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
782 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000783 KnownZero &= Mask;
784 return;
785 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000786 case Instruction::UDiv: {
787 // For the purposes of computing leading zeros we can conservatively
788 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000789 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000790 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
791 ComputeMaskedBits(I->getOperand(0),
792 AllOnes, KnownZero2, KnownOne2, Depth+1);
793 unsigned LeadZ = KnownZero2.countLeadingOnes();
794
795 KnownOne2.clear();
796 KnownZero2.clear();
797 ComputeMaskedBits(I->getOperand(1),
798 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000799 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
800 if (RHSUnknownLeadingOnes != BitWidth)
801 LeadZ = std::min(BitWidth,
802 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000803
804 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
805 return;
806 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000807 case Instruction::Select:
808 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
809 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
810 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
811 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
812
813 // Only known if known in both the LHS and RHS.
814 KnownOne &= KnownOne2;
815 KnownZero &= KnownZero2;
816 return;
817 case Instruction::FPTrunc:
818 case Instruction::FPExt:
819 case Instruction::FPToUI:
820 case Instruction::FPToSI:
821 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000822 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000823 return; // Can't work with floating point.
824 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000825 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000826 // We can't handle these if we don't know the pointer size.
827 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000828 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000829 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000830 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000831 // Note that we handle pointer operands here because of inttoptr/ptrtoint
832 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000833 const Type *SrcTy = I->getOperand(0)->getType();
834 uint32_t SrcBitWidth = TD ?
835 TD->getTypeSizeInBits(SrcTy) :
836 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000837 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000838 MaskIn.zextOrTrunc(SrcBitWidth);
839 KnownZero.zextOrTrunc(SrcBitWidth);
840 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000841 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000842 KnownZero.zextOrTrunc(BitWidth);
843 KnownOne.zextOrTrunc(BitWidth);
844 // Any top bits are known to be zero.
845 if (BitWidth > SrcBitWidth)
846 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000847 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000848 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000849 case Instruction::BitCast: {
850 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000851 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000852 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
853 return;
854 }
855 break;
856 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000857 case Instruction::SExt: {
858 // Compute the bits in the result that are not present in the input.
859 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000860 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000861
Zhou Shengaa305ab2007-03-28 02:19:03 +0000862 APInt MaskIn(Mask);
863 MaskIn.trunc(SrcBitWidth);
864 KnownZero.trunc(SrcBitWidth);
865 KnownOne.trunc(SrcBitWidth);
866 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000867 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000868 KnownZero.zext(BitWidth);
869 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000870
871 // If the sign bit of the input is known set or clear, then we know the
872 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000873 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000874 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000875 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000876 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000877 return;
878 }
879 case Instruction::Shl:
880 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
881 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000882 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000883 APInt Mask2(Mask.lshr(ShiftAmt));
884 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000885 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000886 KnownZero <<= ShiftAmt;
887 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000888 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000889 return;
890 }
891 break;
892 case Instruction::LShr:
893 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
894 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
895 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000896 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000897
898 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000899 APInt Mask2(Mask.shl(ShiftAmt));
900 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000901 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
902 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
903 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000904 // high bits known zero.
905 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000906 return;
907 }
908 break;
909 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000910 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
912 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000913 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000914
915 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000916 APInt Mask2(Mask.shl(ShiftAmt));
917 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000918 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
919 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
920 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
921
Zhou Shengaa305ab2007-03-28 02:19:03 +0000922 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
923 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000924 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000925 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000926 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000927 return;
928 }
929 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000930 case Instruction::Sub: {
931 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
932 // We know that the top bits of C-X are clear if X contains less bits
933 // than C (i.e. no wrap-around can happen). For example, 20-X is
934 // positive if we can prove that X is >= 0 and < 16.
935 if (!CLHS->getValue().isNegative()) {
936 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
937 // NLZ can't be BitWidth with no sign bit
938 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000939 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
940 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000941
Dan Gohman23e8b712008-04-28 17:02:21 +0000942 // If all of the MaskV bits are known to be zero, then we know the
943 // output top bits are zero, because we now know that the output is
944 // from [0-C].
945 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000946 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
947 // Top bits known zero.
948 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000949 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000950 }
951 }
952 }
953 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000954 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000955 // Output known-0 bits are known if clear or set in both the low clear bits
956 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
957 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000958 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
959 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
960 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
961 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
962
963 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
964 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
965 KnownZeroOut = std::min(KnownZeroOut,
966 KnownZero2.countTrailingOnes());
967
968 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000969 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000970 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000971 case Instruction::SRem:
972 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
973 APInt RA = Rem->getValue();
974 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000975 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000976 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
977 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
978
979 // The sign of a remainder is equal to the sign of the first
980 // operand (zero being positive).
981 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
982 KnownZero2 |= ~LowBits;
983 else if (KnownOne2[BitWidth-1])
984 KnownOne2 |= ~LowBits;
985
986 KnownZero |= KnownZero2 & Mask;
987 KnownOne |= KnownOne2 & Mask;
988
989 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
990 }
991 }
992 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000993 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000994 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
995 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +0000996 if (RA.isPowerOf2()) {
997 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000998 APInt Mask2 = LowBits & Mask;
999 KnownZero |= ~LowBits & Mask;
1000 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1001 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001002 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001004 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001005
1006 // Since the result is less than or equal to either operand, any leading
1007 // zero bits in either operand must also exist in the result.
1008 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1009 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1010 Depth+1);
1011 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1012 Depth+1);
1013
1014 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1015 KnownZero2.countLeadingOnes());
1016 KnownOne.clear();
1017 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001018 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001019 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001020
1021 case Instruction::Alloca:
1022 case Instruction::Malloc: {
1023 AllocationInst *AI = cast<AllocationInst>(V);
1024 unsigned Align = AI->getAlignment();
1025 if (Align == 0 && TD) {
1026 if (isa<AllocaInst>(AI))
1027 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1028 else if (isa<MallocInst>(AI)) {
1029 // Malloc returns maximally aligned memory.
1030 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1031 Align =
1032 std::max(Align,
1033 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1034 Align =
1035 std::max(Align,
1036 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1037 }
1038 }
1039
1040 if (Align > 0)
1041 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1042 CountTrailingZeros_32(Align));
1043 break;
1044 }
1045 case Instruction::GetElementPtr: {
1046 // Analyze all of the subscripts of this getelementptr instruction
1047 // to determine if we can prove known low zero bits.
1048 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1049 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1050 ComputeMaskedBits(I->getOperand(0), LocalMask,
1051 LocalKnownZero, LocalKnownOne, Depth+1);
1052 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1053
1054 gep_type_iterator GTI = gep_type_begin(I);
1055 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1056 Value *Index = I->getOperand(i);
1057 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1058 // Handle struct member offset arithmetic.
1059 if (!TD) return;
1060 const StructLayout *SL = TD->getStructLayout(STy);
1061 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1062 uint64_t Offset = SL->getElementOffset(Idx);
1063 TrailZ = std::min(TrailZ,
1064 CountTrailingZeros_64(Offset));
1065 } else {
1066 // Handle array index arithmetic.
1067 const Type *IndexedTy = GTI.getIndexedType();
1068 if (!IndexedTy->isSized()) return;
1069 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1070 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1071 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1072 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1073 ComputeMaskedBits(Index, LocalMask,
1074 LocalKnownZero, LocalKnownOne, Depth+1);
1075 TrailZ = std::min(TrailZ,
1076 CountTrailingZeros_64(TypeSize) +
1077 LocalKnownZero.countTrailingOnes());
1078 }
1079 }
1080
1081 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1082 break;
1083 }
1084 case Instruction::PHI: {
1085 PHINode *P = cast<PHINode>(I);
1086 // Handle the case of a simple two-predecessor recurrence PHI.
1087 // There's a lot more that could theoretically be done here, but
1088 // this is sufficient to catch some interesting cases.
1089 if (P->getNumIncomingValues() == 2) {
1090 for (unsigned i = 0; i != 2; ++i) {
1091 Value *L = P->getIncomingValue(i);
1092 Value *R = P->getIncomingValue(!i);
1093 User *LU = dyn_cast<User>(L);
1094 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1095 // Check for operations that have the property that if
1096 // both their operands have low zero bits, the result
1097 // will have low zero bits.
1098 if (Opcode == Instruction::Add ||
1099 Opcode == Instruction::Sub ||
1100 Opcode == Instruction::And ||
1101 Opcode == Instruction::Or ||
1102 Opcode == Instruction::Mul) {
1103 Value *LL = LU->getOperand(0);
1104 Value *LR = LU->getOperand(1);
1105 // Find a recurrence.
1106 if (LL == I)
1107 L = LR;
1108 else if (LR == I)
1109 L = LL;
1110 else
1111 break;
1112 // Ok, we have a PHI of the form L op= R. Check for low
1113 // zero bits.
1114 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1115 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1116 Mask2 = APInt::getLowBitsSet(BitWidth,
1117 KnownZero2.countTrailingOnes());
1118 KnownOne2.clear();
1119 KnownZero2.clear();
1120 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1121 KnownZero = Mask &
1122 APInt::getLowBitsSet(BitWidth,
1123 KnownZero2.countTrailingOnes());
1124 break;
1125 }
1126 }
1127 }
1128 break;
1129 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001130 case Instruction::Call:
1131 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1132 switch (II->getIntrinsicID()) {
1133 default: break;
1134 case Intrinsic::ctpop:
1135 case Intrinsic::ctlz:
1136 case Intrinsic::cttz: {
1137 unsigned LowBits = Log2_32(BitWidth)+1;
1138 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1139 break;
1140 }
1141 }
1142 }
1143 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001144 }
1145}
1146
Reid Spencere7816b52007-03-08 01:52:58 +00001147/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1148/// this predicate to simplify operations downstream. Mask is known to be zero
1149/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001150bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1151 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001152 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001153 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1154 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1155 return (KnownZero & Mask) == Mask;
1156}
1157
Chris Lattner255d8912006-02-11 09:31:47 +00001158/// ShrinkDemandedConstant - Check to see if the specified operand of the
1159/// specified instruction is a constant integer. If so, check to see if there
1160/// are any bits set in the constant that are not demanded. If so, shrink the
1161/// constant and return true.
1162static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001163 APInt Demanded) {
1164 assert(I && "No instruction?");
1165 assert(OpNo < I->getNumOperands() && "Operand index too large");
1166
1167 // If the operand is not a constant integer, nothing to do.
1168 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1169 if (!OpC) return false;
1170
1171 // If there are no bits set that aren't demanded, nothing to do.
1172 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1173 if ((~Demanded & OpC->getValue()) == 0)
1174 return false;
1175
1176 // This instruction is producing bits that are not demanded. Shrink the RHS.
1177 Demanded &= OpC->getValue();
1178 I->setOperand(OpNo, ConstantInt::get(Demanded));
1179 return true;
1180}
1181
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001182// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1183// set of known zero and one bits, compute the maximum and minimum values that
1184// could have the specified known zero and known one bits, returning them in
1185// min/max.
1186static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001187 const APInt& KnownZero,
1188 const APInt& KnownOne,
1189 APInt& Min, APInt& Max) {
1190 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1191 assert(KnownZero.getBitWidth() == BitWidth &&
1192 KnownOne.getBitWidth() == BitWidth &&
1193 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1194 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001195 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001196
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001197 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1198 // bit if it is unknown.
1199 Min = KnownOne;
1200 Max = KnownOne|UnknownBits;
1201
Zhou Sheng4acf1552007-03-28 05:15:57 +00001202 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001203 Min.set(BitWidth-1);
1204 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001205 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001206}
1207
1208// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1209// a set of known zero and one bits, compute the maximum and minimum values that
1210// could have the specified known zero and known one bits, returning them in
1211// min/max.
1212static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001213 const APInt &KnownZero,
1214 const APInt &KnownOne,
1215 APInt &Min, APInt &Max) {
1216 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001217 assert(KnownZero.getBitWidth() == BitWidth &&
1218 KnownOne.getBitWidth() == BitWidth &&
1219 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1220 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001221 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001222
1223 // The minimum value is when the unknown bits are all zeros.
1224 Min = KnownOne;
1225 // The maximum value is when the unknown bits are all ones.
1226 Max = KnownOne|UnknownBits;
1227}
Chris Lattner255d8912006-02-11 09:31:47 +00001228
Reid Spencer8cb68342007-03-12 17:25:59 +00001229/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1230/// value based on the demanded bits. When this function is called, it is known
1231/// that only the bits set in DemandedMask of the result of V are ever used
1232/// downstream. Consequently, depending on the mask and V, it may be possible
1233/// to replace V with a constant or one of its operands. In such cases, this
1234/// function does the replacement and returns true. In all other cases, it
1235/// returns false after analyzing the expression and setting KnownOne and known
1236/// to be one in the expression. KnownZero contains all the bits that are known
1237/// to be zero in the expression. These are provided to potentially allow the
1238/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1239/// the expression. KnownOne and KnownZero always follow the invariant that
1240/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1241/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1242/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1243/// and KnownOne must all be the same.
1244bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1245 APInt& KnownZero, APInt& KnownOne,
1246 unsigned Depth) {
1247 assert(V != 0 && "Null pointer of Value???");
1248 assert(Depth <= 6 && "Limit Search Depth");
1249 uint32_t BitWidth = DemandedMask.getBitWidth();
1250 const IntegerType *VTy = cast<IntegerType>(V->getType());
1251 assert(VTy->getBitWidth() == BitWidth &&
1252 KnownZero.getBitWidth() == BitWidth &&
1253 KnownOne.getBitWidth() == BitWidth &&
1254 "Value *V, DemandedMask, KnownZero and KnownOne \
1255 must have same BitWidth");
1256 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1257 // We know all of the bits for a constant!
1258 KnownOne = CI->getValue() & DemandedMask;
1259 KnownZero = ~KnownOne & DemandedMask;
1260 return false;
1261 }
1262
Zhou Sheng96704452007-03-14 03:21:24 +00001263 KnownZero.clear();
1264 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 if (!V->hasOneUse()) { // Other users may use these bits.
1266 if (Depth != 0) { // Not at the root.
1267 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1268 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1269 return false;
1270 }
1271 // If this is the root being simplified, allow it to have multiple uses,
1272 // just set the DemandedMask to all bits.
1273 DemandedMask = APInt::getAllOnesValue(BitWidth);
1274 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1275 if (V != UndefValue::get(VTy))
1276 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1277 return false;
1278 } else if (Depth == 6) { // Limit search depth.
1279 return false;
1280 }
1281
1282 Instruction *I = dyn_cast<Instruction>(V);
1283 if (!I) return false; // Only analyze instructions.
1284
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1286 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1287 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001288 default:
1289 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1290 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 case Instruction::And:
1292 // If either the LHS or the RHS are Zero, the result is zero.
1293 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1294 RHSKnownZero, RHSKnownOne, Depth+1))
1295 return true;
1296 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1297 "Bits known to be one AND zero?");
1298
1299 // If something is known zero on the RHS, the bits aren't demanded on the
1300 // LHS.
1301 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1302 LHSKnownZero, LHSKnownOne, Depth+1))
1303 return true;
1304 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1305 "Bits known to be one AND zero?");
1306
1307 // If all of the demanded bits are known 1 on one side, return the other.
1308 // These bits cannot contribute to the result of the 'and'.
1309 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1310 (DemandedMask & ~LHSKnownZero))
1311 return UpdateValueUsesWith(I, I->getOperand(0));
1312 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1313 (DemandedMask & ~RHSKnownZero))
1314 return UpdateValueUsesWith(I, I->getOperand(1));
1315
1316 // If all of the demanded bits in the inputs are known zeros, return zero.
1317 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1318 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1319
1320 // If the RHS is a constant, see if we can simplify it.
1321 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1322 return UpdateValueUsesWith(I, I);
1323
1324 // Output known-1 bits are only known if set in both the LHS & RHS.
1325 RHSKnownOne &= LHSKnownOne;
1326 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1327 RHSKnownZero |= LHSKnownZero;
1328 break;
1329 case Instruction::Or:
1330 // If either the LHS or the RHS are One, the result is One.
1331 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1332 RHSKnownZero, RHSKnownOne, Depth+1))
1333 return true;
1334 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1335 "Bits known to be one AND zero?");
1336 // If something is known one on the RHS, the bits aren't demanded on the
1337 // LHS.
1338 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1339 LHSKnownZero, LHSKnownOne, Depth+1))
1340 return true;
1341 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1343
1344 // If all of the demanded bits are known zero on one side, return the other.
1345 // These bits cannot contribute to the result of the 'or'.
1346 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1347 (DemandedMask & ~LHSKnownOne))
1348 return UpdateValueUsesWith(I, I->getOperand(0));
1349 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1350 (DemandedMask & ~RHSKnownOne))
1351 return UpdateValueUsesWith(I, I->getOperand(1));
1352
1353 // If all of the potentially set bits on one side are known to be set on
1354 // the other side, just use the 'other' side.
1355 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1356 (DemandedMask & (~RHSKnownZero)))
1357 return UpdateValueUsesWith(I, I->getOperand(0));
1358 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1359 (DemandedMask & (~LHSKnownZero)))
1360 return UpdateValueUsesWith(I, I->getOperand(1));
1361
1362 // If the RHS is a constant, see if we can simplify it.
1363 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1364 return UpdateValueUsesWith(I, I);
1365
1366 // Output known-0 bits are only known if clear in both the LHS & RHS.
1367 RHSKnownZero &= LHSKnownZero;
1368 // Output known-1 are known to be set if set in either the LHS | RHS.
1369 RHSKnownOne |= LHSKnownOne;
1370 break;
1371 case Instruction::Xor: {
1372 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1373 RHSKnownZero, RHSKnownOne, Depth+1))
1374 return true;
1375 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1376 "Bits known to be one AND zero?");
1377 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1378 LHSKnownZero, LHSKnownOne, Depth+1))
1379 return true;
1380 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1381 "Bits known to be one AND zero?");
1382
1383 // If all of the demanded bits are known zero on one side, return the other.
1384 // These bits cannot contribute to the result of the 'xor'.
1385 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1386 return UpdateValueUsesWith(I, I->getOperand(0));
1387 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1388 return UpdateValueUsesWith(I, I->getOperand(1));
1389
1390 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1391 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1392 (RHSKnownOne & LHSKnownOne);
1393 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1394 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1395 (RHSKnownOne & LHSKnownZero);
1396
1397 // If all of the demanded bits are known to be zero on one side or the
1398 // other, turn this into an *inclusive* or.
1399 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1400 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1401 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001402 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001403 I->getName());
1404 InsertNewInstBefore(Or, *I);
1405 return UpdateValueUsesWith(I, Or);
1406 }
1407
1408 // If all of the demanded bits on one side are known, and all of the set
1409 // bits on that side are also known to be set on the other side, turn this
1410 // into an AND, as we know the bits will be cleared.
1411 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1412 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1413 // all known
1414 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1415 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1416 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001417 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001418 InsertNewInstBefore(And, *I);
1419 return UpdateValueUsesWith(I, And);
1420 }
1421 }
1422
1423 // If the RHS is a constant, see if we can simplify it.
1424 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1425 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1426 return UpdateValueUsesWith(I, I);
1427
1428 RHSKnownZero = KnownZeroOut;
1429 RHSKnownOne = KnownOneOut;
1430 break;
1431 }
1432 case Instruction::Select:
1433 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1434 RHSKnownZero, RHSKnownOne, Depth+1))
1435 return true;
1436 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1437 LHSKnownZero, LHSKnownOne, Depth+1))
1438 return true;
1439 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1440 "Bits known to be one AND zero?");
1441 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1442 "Bits known to be one AND zero?");
1443
1444 // If the operands are constants, see if we can simplify them.
1445 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1446 return UpdateValueUsesWith(I, I);
1447 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1448 return UpdateValueUsesWith(I, I);
1449
1450 // Only known if known in both the LHS and RHS.
1451 RHSKnownOne &= LHSKnownOne;
1452 RHSKnownZero &= LHSKnownZero;
1453 break;
1454 case Instruction::Trunc: {
1455 uint32_t truncBf =
1456 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001457 DemandedMask.zext(truncBf);
1458 RHSKnownZero.zext(truncBf);
1459 RHSKnownOne.zext(truncBf);
1460 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1461 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001462 return true;
1463 DemandedMask.trunc(BitWidth);
1464 RHSKnownZero.trunc(BitWidth);
1465 RHSKnownOne.trunc(BitWidth);
1466 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1467 "Bits known to be one AND zero?");
1468 break;
1469 }
1470 case Instruction::BitCast:
1471 if (!I->getOperand(0)->getType()->isInteger())
1472 return false;
1473
1474 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1475 RHSKnownZero, RHSKnownOne, Depth+1))
1476 return true;
1477 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1478 "Bits known to be one AND zero?");
1479 break;
1480 case Instruction::ZExt: {
1481 // Compute the bits in the result that are not present in the input.
1482 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001483 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001484
Zhou Shengd48653a2007-03-29 04:45:55 +00001485 DemandedMask.trunc(SrcBitWidth);
1486 RHSKnownZero.trunc(SrcBitWidth);
1487 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001488 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1489 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001490 return true;
1491 DemandedMask.zext(BitWidth);
1492 RHSKnownZero.zext(BitWidth);
1493 RHSKnownOne.zext(BitWidth);
1494 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1495 "Bits known to be one AND zero?");
1496 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001497 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001498 break;
1499 }
1500 case Instruction::SExt: {
1501 // Compute the bits in the result that are not present in the input.
1502 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001503 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001504
Reid Spencer8cb68342007-03-12 17:25:59 +00001505 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001506 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001507
Zhou Sheng01542f32007-03-29 02:26:30 +00001508 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001509 // If any of the sign extended bits are demanded, we know that the sign
1510 // bit is demanded.
1511 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001512 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001513
Zhou Shengd48653a2007-03-29 04:45:55 +00001514 InputDemandedBits.trunc(SrcBitWidth);
1515 RHSKnownZero.trunc(SrcBitWidth);
1516 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001517 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1518 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001519 return true;
1520 InputDemandedBits.zext(BitWidth);
1521 RHSKnownZero.zext(BitWidth);
1522 RHSKnownOne.zext(BitWidth);
1523 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1524 "Bits known to be one AND zero?");
1525
1526 // If the sign bit of the input is known set or clear, then we know the
1527 // top bits of the result.
1528
1529 // If the input sign bit is known zero, or if the NewBits are not demanded
1530 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001531 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001532 {
1533 // Convert to ZExt cast
1534 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1535 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001536 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001537 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001538 }
1539 break;
1540 }
1541 case Instruction::Add: {
1542 // Figure out what the input bits are. If the top bits of the and result
1543 // are not demanded, then the add doesn't demand them from its input
1544 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001545 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001546
1547 // If there is a constant on the RHS, there are a variety of xformations
1548 // we can do.
1549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1550 // If null, this should be simplified elsewhere. Some of the xforms here
1551 // won't work if the RHS is zero.
1552 if (RHS->isZero())
1553 break;
1554
1555 // If the top bit of the output is demanded, demand everything from the
1556 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001557 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001558
1559 // Find information about known zero/one bits in the input.
1560 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1561 LHSKnownZero, LHSKnownOne, Depth+1))
1562 return true;
1563
1564 // If the RHS of the add has bits set that can't affect the input, reduce
1565 // the constant.
1566 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1567 return UpdateValueUsesWith(I, I);
1568
1569 // Avoid excess work.
1570 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1571 break;
1572
1573 // Turn it into OR if input bits are zero.
1574 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1575 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001576 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001577 I->getName());
1578 InsertNewInstBefore(Or, *I);
1579 return UpdateValueUsesWith(I, Or);
1580 }
1581
1582 // We can say something about the output known-zero and known-one bits,
1583 // depending on potential carries from the input constant and the
1584 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1585 // bits set and the RHS constant is 0x01001, then we know we have a known
1586 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1587
1588 // To compute this, we first compute the potential carry bits. These are
1589 // the bits which may be modified. I'm not aware of a better way to do
1590 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001591 const APInt& RHSVal = RHS->getValue();
1592 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001593
1594 // Now that we know which bits have carries, compute the known-1/0 sets.
1595
1596 // Bits are known one if they are known zero in one operand and one in the
1597 // other, and there is no input carry.
1598 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1599 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1600
1601 // Bits are known zero if they are known zero in both operands and there
1602 // is no input carry.
1603 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1604 } else {
1605 // If the high-bits of this ADD are not demanded, then it does not demand
1606 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001607 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001608 // Right fill the mask of bits for this ADD to demand the most
1609 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001610 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001611 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1612 LHSKnownZero, LHSKnownOne, Depth+1))
1613 return true;
1614 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1615 LHSKnownZero, LHSKnownOne, Depth+1))
1616 return true;
1617 }
1618 }
1619 break;
1620 }
1621 case Instruction::Sub:
1622 // If the high-bits of this SUB are not demanded, then it does not demand
1623 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001624 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001625 // Right fill the mask of bits for this SUB to demand the most
1626 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001627 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001628 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001629 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1630 LHSKnownZero, LHSKnownOne, Depth+1))
1631 return true;
1632 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1633 LHSKnownZero, LHSKnownOne, Depth+1))
1634 return true;
1635 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001636 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1637 // the known zeros and ones.
1638 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001639 break;
1640 case Instruction::Shl:
1641 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001642 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001643 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1644 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001645 RHSKnownZero, RHSKnownOne, Depth+1))
1646 return true;
1647 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1648 "Bits known to be one AND zero?");
1649 RHSKnownZero <<= ShiftAmt;
1650 RHSKnownOne <<= ShiftAmt;
1651 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001652 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001653 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001654 }
1655 break;
1656 case Instruction::LShr:
1657 // For a logical shift right
1658 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001659 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001660
Reid Spencer8cb68342007-03-12 17:25:59 +00001661 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001662 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1663 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001664 RHSKnownZero, RHSKnownOne, Depth+1))
1665 return true;
1666 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1667 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001668 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1669 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001670 if (ShiftAmt) {
1671 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001672 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001673 RHSKnownZero |= HighBits; // high bits known zero.
1674 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001675 }
1676 break;
1677 case Instruction::AShr:
1678 // If this is an arithmetic shift right and only the low-bit is set, we can
1679 // always convert this into a logical shr, even if the shift amount is
1680 // variable. The low bit of the shift cannot be an input sign bit unless
1681 // the shift amount is >= the size of the datatype, which is undefined.
1682 if (DemandedMask == 1) {
1683 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001684 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001685 I->getOperand(0), I->getOperand(1), I->getName());
1686 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1687 return UpdateValueUsesWith(I, NewVal);
1688 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001689
1690 // If the sign bit is the only bit demanded by this ashr, then there is no
1691 // need to do it, the shift doesn't change the high bit.
1692 if (DemandedMask.isSignBit())
1693 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001694
1695 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001696 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001697
Reid Spencer8cb68342007-03-12 17:25:59 +00001698 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001699 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001700 // If any of the "high bits" are demanded, we should set the sign bit as
1701 // demanded.
1702 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1703 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001704 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001705 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001706 RHSKnownZero, RHSKnownOne, Depth+1))
1707 return true;
1708 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1709 "Bits known to be one AND zero?");
1710 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001711 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001712 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1713 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1714
1715 // Handle the sign bits.
1716 APInt SignBit(APInt::getSignBit(BitWidth));
1717 // Adjust to where it is now in the mask.
1718 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1719
1720 // If the input sign bit is known to be zero, or if none of the top bits
1721 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001722 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001723 (HighBits & ~DemandedMask) == HighBits) {
1724 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001725 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001726 I->getOperand(0), SA, I->getName());
1727 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1728 return UpdateValueUsesWith(I, NewVal);
1729 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1730 RHSKnownOne |= HighBits;
1731 }
1732 }
1733 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001734 case Instruction::SRem:
1735 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1736 APInt RA = Rem->getValue();
1737 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001738 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001739 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1740 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1741 LHSKnownZero, LHSKnownOne, Depth+1))
1742 return true;
1743
1744 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1745 LHSKnownZero |= ~LowBits;
1746 else if (LHSKnownOne[BitWidth-1])
1747 LHSKnownOne |= ~LowBits;
1748
1749 KnownZero |= LHSKnownZero & DemandedMask;
1750 KnownOne |= LHSKnownOne & DemandedMask;
1751
1752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1753 }
1754 }
1755 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001756 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001757 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1758 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001759 if (RA.isPowerOf2()) {
1760 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001761 APInt Mask2 = LowBits & DemandedMask;
1762 KnownZero |= ~LowBits & DemandedMask;
1763 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1764 KnownZero, KnownOne, Depth+1))
1765 return true;
1766
1767 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001768 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001769 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001770 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001771
1772 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1773 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001774 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1775 KnownZero2, KnownOne2, Depth+1))
1776 return true;
1777
Dan Gohman23e8b712008-04-28 17:02:21 +00001778 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001779 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001780 KnownZero2, KnownOne2, Depth+1))
1781 return true;
1782
1783 Leaders = std::max(Leaders,
1784 KnownZero2.countLeadingOnes());
1785 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001786 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001787 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001788 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001789
1790 // If the client is only demanding bits that we know, return the known
1791 // constant.
1792 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1793 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1794 return false;
1795}
1796
Chris Lattner867b99f2006-10-05 06:55:50 +00001797
1798/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1799/// 64 or fewer elements. DemandedElts contains the set of elements that are
1800/// actually used by the caller. This method analyzes which elements of the
1801/// operand are undef and returns that information in UndefElts.
1802///
1803/// If the information about demanded elements can be used to simplify the
1804/// operation, the operation is simplified, then the resultant value is
1805/// returned. This returns null if no change was made.
1806Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1807 uint64_t &UndefElts,
1808 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001809 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001810 assert(VWidth <= 64 && "Vector too wide to analyze!");
1811 uint64_t EltMask = ~0ULL >> (64-VWidth);
1812 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1813 "Invalid DemandedElts!");
1814
1815 if (isa<UndefValue>(V)) {
1816 // If the entire vector is undefined, just return this info.
1817 UndefElts = EltMask;
1818 return 0;
1819 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1820 UndefElts = EltMask;
1821 return UndefValue::get(V->getType());
1822 }
1823
1824 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001825 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1826 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001827 Constant *Undef = UndefValue::get(EltTy);
1828
1829 std::vector<Constant*> Elts;
1830 for (unsigned i = 0; i != VWidth; ++i)
1831 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1832 Elts.push_back(Undef);
1833 UndefElts |= (1ULL << i);
1834 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1835 Elts.push_back(Undef);
1836 UndefElts |= (1ULL << i);
1837 } else { // Otherwise, defined.
1838 Elts.push_back(CP->getOperand(i));
1839 }
1840
1841 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001842 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001843 return NewCP != CP ? NewCP : 0;
1844 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001845 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001846 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001847 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001848 Constant *Zero = Constant::getNullValue(EltTy);
1849 Constant *Undef = UndefValue::get(EltTy);
1850 std::vector<Constant*> Elts;
1851 for (unsigned i = 0; i != VWidth; ++i)
1852 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1853 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001854 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001855 }
1856
1857 if (!V->hasOneUse()) { // Other users may use these bits.
1858 if (Depth != 0) { // Not at the root.
1859 // TODO: Just compute the UndefElts information recursively.
1860 return false;
1861 }
1862 return false;
1863 } else if (Depth == 10) { // Limit search depth.
1864 return false;
1865 }
1866
1867 Instruction *I = dyn_cast<Instruction>(V);
1868 if (!I) return false; // Only analyze instructions.
1869
1870 bool MadeChange = false;
1871 uint64_t UndefElts2;
1872 Value *TmpV;
1873 switch (I->getOpcode()) {
1874 default: break;
1875
1876 case Instruction::InsertElement: {
1877 // If this is a variable index, we don't know which element it overwrites.
1878 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001879 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001880 if (Idx == 0) {
1881 // Note that we can't propagate undef elt info, because we don't know
1882 // which elt is getting updated.
1883 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1884 UndefElts2, Depth+1);
1885 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1886 break;
1887 }
1888
1889 // If this is inserting an element that isn't demanded, remove this
1890 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001891 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001892 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1893 return AddSoonDeadInstToWorklist(*I, 0);
1894
1895 // Otherwise, the element inserted overwrites whatever was there, so the
1896 // input demanded set is simpler than the output set.
1897 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1898 DemandedElts & ~(1ULL << IdxNo),
1899 UndefElts, Depth+1);
1900 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1901
1902 // The inserted element is defined.
1903 UndefElts |= 1ULL << IdxNo;
1904 break;
1905 }
Chris Lattner69878332007-04-14 22:29:23 +00001906 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001907 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001908 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1909 if (!VTy) break;
1910 unsigned InVWidth = VTy->getNumElements();
1911 uint64_t InputDemandedElts = 0;
1912 unsigned Ratio;
1913
1914 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001915 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001916 // elements as are demanded of us.
1917 Ratio = 1;
1918 InputDemandedElts = DemandedElts;
1919 } else if (VWidth > InVWidth) {
1920 // Untested so far.
1921 break;
1922
1923 // If there are more elements in the result than there are in the source,
1924 // then an input element is live if any of the corresponding output
1925 // elements are live.
1926 Ratio = VWidth/InVWidth;
1927 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1928 if (DemandedElts & (1ULL << OutIdx))
1929 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1930 }
1931 } else {
1932 // Untested so far.
1933 break;
1934
1935 // If there are more elements in the source than there are in the result,
1936 // then an input element is live if the corresponding output element is
1937 // live.
1938 Ratio = InVWidth/VWidth;
1939 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1940 if (DemandedElts & (1ULL << InIdx/Ratio))
1941 InputDemandedElts |= 1ULL << InIdx;
1942 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001943
Chris Lattner69878332007-04-14 22:29:23 +00001944 // div/rem demand all inputs, because they don't want divide by zero.
1945 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1946 UndefElts2, Depth+1);
1947 if (TmpV) {
1948 I->setOperand(0, TmpV);
1949 MadeChange = true;
1950 }
1951
1952 UndefElts = UndefElts2;
1953 if (VWidth > InVWidth) {
1954 assert(0 && "Unimp");
1955 // If there are more elements in the result than there are in the source,
1956 // then an output element is undef if the corresponding input element is
1957 // undef.
1958 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1959 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1960 UndefElts |= 1ULL << OutIdx;
1961 } else if (VWidth < InVWidth) {
1962 assert(0 && "Unimp");
1963 // If there are more elements in the source than there are in the result,
1964 // then a result element is undef if all of the corresponding input
1965 // elements are undef.
1966 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1967 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1968 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1969 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1970 }
1971 break;
1972 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001973 case Instruction::And:
1974 case Instruction::Or:
1975 case Instruction::Xor:
1976 case Instruction::Add:
1977 case Instruction::Sub:
1978 case Instruction::Mul:
1979 // div/rem demand all inputs, because they don't want divide by zero.
1980 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1981 UndefElts, Depth+1);
1982 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1983 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1984 UndefElts2, Depth+1);
1985 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1986
1987 // Output elements are undefined if both are undefined. Consider things
1988 // like undef&0. The result is known zero, not undef.
1989 UndefElts &= UndefElts2;
1990 break;
1991
1992 case Instruction::Call: {
1993 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1994 if (!II) break;
1995 switch (II->getIntrinsicID()) {
1996 default: break;
1997
1998 // Binary vector operations that work column-wise. A dest element is a
1999 // function of the corresponding input elements from the two inputs.
2000 case Intrinsic::x86_sse_sub_ss:
2001 case Intrinsic::x86_sse_mul_ss:
2002 case Intrinsic::x86_sse_min_ss:
2003 case Intrinsic::x86_sse_max_ss:
2004 case Intrinsic::x86_sse2_sub_sd:
2005 case Intrinsic::x86_sse2_mul_sd:
2006 case Intrinsic::x86_sse2_min_sd:
2007 case Intrinsic::x86_sse2_max_sd:
2008 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2009 UndefElts, Depth+1);
2010 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2011 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2012 UndefElts2, Depth+1);
2013 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2014
2015 // If only the low elt is demanded and this is a scalarizable intrinsic,
2016 // scalarize it now.
2017 if (DemandedElts == 1) {
2018 switch (II->getIntrinsicID()) {
2019 default: break;
2020 case Intrinsic::x86_sse_sub_ss:
2021 case Intrinsic::x86_sse_mul_ss:
2022 case Intrinsic::x86_sse2_sub_sd:
2023 case Intrinsic::x86_sse2_mul_sd:
2024 // TODO: Lower MIN/MAX/ABS/etc
2025 Value *LHS = II->getOperand(1);
2026 Value *RHS = II->getOperand(2);
2027 // Extract the element as scalars.
2028 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2029 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2030
2031 switch (II->getIntrinsicID()) {
2032 default: assert(0 && "Case stmts out of sync!");
2033 case Intrinsic::x86_sse_sub_ss:
2034 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002035 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002036 II->getName()), *II);
2037 break;
2038 case Intrinsic::x86_sse_mul_ss:
2039 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002041 II->getName()), *II);
2042 break;
2043 }
2044
2045 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002046 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2047 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002048 InsertNewInstBefore(New, *II);
2049 AddSoonDeadInstToWorklist(*II, 0);
2050 return New;
2051 }
2052 }
2053
2054 // Output elements are undefined if both are undefined. Consider things
2055 // like undef&0. The result is known zero, not undef.
2056 UndefElts &= UndefElts2;
2057 break;
2058 }
2059 break;
2060 }
2061 }
2062 return MadeChange ? I : 0;
2063}
2064
Dan Gohman45b4e482008-05-19 22:14:15 +00002065/// ComputeNumSignBits - Return the number of times the sign bit of the
2066/// register is replicated into the other bits. We know that at least 1 bit
2067/// is always equal to the sign bit (itself), but other cases can give us
2068/// information. For example, immediately after an "ashr X, 2", we know that
2069/// the top 3 bits are all equal to each other, so we return 3.
2070///
2071unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2072 const IntegerType *Ty = cast<IntegerType>(V->getType());
2073 unsigned TyBits = Ty->getBitWidth();
2074 unsigned Tmp, Tmp2;
2075
2076 if (Depth == 6)
2077 return 1; // Limit search depth.
2078
2079 User *U = dyn_cast<User>(V);
2080 switch (getOpcode(V)) {
2081 default: break;
2082 case Instruction::SExt:
2083 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2084 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2085
2086 case Instruction::AShr:
2087 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002088 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002089 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2090 Tmp += C->getZExtValue();
2091 if (Tmp > TyBits) Tmp = TyBits;
2092 }
2093 return Tmp;
2094 case Instruction::Shl:
2095 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2096 // shl destroys sign bits.
2097 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2098 if (C->getZExtValue() >= TyBits || // Bad shift.
2099 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2100 return Tmp - C->getZExtValue();
2101 }
2102 break;
2103 case Instruction::And:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002104 // Logical binary ops preserve the number of sign bits at the worst.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106 if (Tmp != 1) {
2107 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2108 Tmp = std::min(Tmp, Tmp2);
2109 }
2110
2111 // X & C has sign bits equal to C if C's top bits are zeros.
2112 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2113 // See what bits are known to be zero on the output.
2114 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2115 APInt Mask = APInt::getAllOnesValue(TyBits);
2116 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2117
2118 KnownZero |= ~C->getValue();
2119 // If we know that we have leading zeros, we know we have at least that
2120 // many sign bits.
2121 Tmp = std::max(Tmp, KnownZero.countLeadingOnes());
2122 }
2123 return Tmp;
2124
Dan Gohman45b4e482008-05-19 22:14:15 +00002125 case Instruction::Or:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002126 // Logical binary ops preserve the number of sign bits at the worst.
2127 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2128 if (Tmp != 1) {
2129 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2130 Tmp = std::min(Tmp, Tmp2);
2131 }
2132 // X & C has sign bits equal to C if C's top bits are zeros.
2133 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2134 // See what bits are known to be one on the output.
2135 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2136 APInt Mask = APInt::getAllOnesValue(TyBits);
2137 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2138
2139 KnownOne |= C->getValue();
2140 // If we know that we have leading ones, we know we have at least that
2141 // many sign bits.
2142 Tmp = std::max(Tmp, KnownOne.countLeadingOnes());
2143 }
2144 return Tmp;
2145
Dan Gohman45b4e482008-05-19 22:14:15 +00002146 case Instruction::Xor: // NOT is handled here.
2147 // Logical binary ops preserve the number of sign bits.
2148 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2149 if (Tmp == 1) return 1; // Early out.
2150 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2151 return std::min(Tmp, Tmp2);
2152
2153 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002154 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002155 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002156 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002157 return std::min(Tmp, Tmp2);
2158
2159 case Instruction::Add:
2160 // Add can have at most one carry bit. Thus we know that the output
2161 // is, at worst, one more bit than the inputs.
2162 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2163 if (Tmp == 1) return 1; // Early out.
2164
2165 // Special case decrementing a value (ADD X, -1):
2166 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2167 if (CRHS->isAllOnesValue()) {
2168 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2169 APInt Mask = APInt::getAllOnesValue(TyBits);
2170 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2171
2172 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2173 // sign bits set.
2174 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2175 return TyBits;
2176
2177 // If we are subtracting one from a positive number, there is no carry
2178 // out of the result.
2179 if (KnownZero.isNegative())
2180 return Tmp;
2181 }
2182
2183 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2184 if (Tmp2 == 1) return 1;
2185 return std::min(Tmp, Tmp2)-1;
2186 break;
2187
2188 case Instruction::Sub:
2189 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2190 if (Tmp2 == 1) return 1;
2191
2192 // Handle NEG.
2193 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2194 if (CLHS->isNullValue()) {
2195 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2196 APInt Mask = APInt::getAllOnesValue(TyBits);
2197 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2198 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2199 // sign bits set.
2200 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2201 return TyBits;
2202
2203 // If the input is known to be positive (the sign bit is known clear),
2204 // the output of the NEG has the same number of sign bits as the input.
2205 if (KnownZero.isNegative())
2206 return Tmp2;
2207
2208 // Otherwise, we treat this like a SUB.
2209 }
2210
2211 // Sub can have at most one carry bit. Thus we know that the output
2212 // is, at worst, one more bit than the inputs.
2213 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2214 if (Tmp == 1) return 1; // Early out.
2215 return std::min(Tmp, Tmp2)-1;
2216 break;
2217 case Instruction::Trunc:
2218 // FIXME: it's tricky to do anything useful for this, but it is an important
2219 // case for targets like X86.
2220 break;
2221 }
2222
2223 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2224 // use this information.
2225 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2226 APInt Mask = APInt::getAllOnesValue(TyBits);
2227 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2228
2229 if (KnownZero.isNegative()) { // sign bit is 0
2230 Mask = KnownZero;
2231 } else if (KnownOne.isNegative()) { // sign bit is 1;
2232 Mask = KnownOne;
2233 } else {
2234 // Nothing known.
2235 return 1;
2236 }
2237
2238 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2239 // the number of identical bits in the top of the input value.
2240 Mask = ~Mask;
2241 Mask <<= Mask.getBitWidth()-TyBits;
2242 // Return # leading zeros. We use 'min' here in case Val was zero before
2243 // shifting. We don't want to return '64' as for an i32 "0".
2244 return std::min(TyBits, Mask.countLeadingZeros());
2245}
2246
2247
Chris Lattner564a7272003-08-13 19:01:45 +00002248/// AssociativeOpt - Perform an optimization on an associative operator. This
2249/// function is designed to check a chain of associative operators for a
2250/// potential to apply a certain optimization. Since the optimization may be
2251/// applicable if the expression was reassociated, this checks the chain, then
2252/// reassociates the expression as necessary to expose the optimization
2253/// opportunity. This makes use of a special Functor, which must define
2254/// 'shouldApply' and 'apply' methods.
2255///
2256template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002257static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002258 unsigned Opcode = Root.getOpcode();
2259 Value *LHS = Root.getOperand(0);
2260
2261 // Quick check, see if the immediate LHS matches...
2262 if (F.shouldApply(LHS))
2263 return F.apply(Root);
2264
2265 // Otherwise, if the LHS is not of the same opcode as the root, return.
2266 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002267 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002268 // Should we apply this transform to the RHS?
2269 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2270
2271 // If not to the RHS, check to see if we should apply to the LHS...
2272 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2273 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2274 ShouldApply = true;
2275 }
2276
2277 // If the functor wants to apply the optimization to the RHS of LHSI,
2278 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2279 if (ShouldApply) {
2280 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002281
Chris Lattner564a7272003-08-13 19:01:45 +00002282 // Now all of the instructions are in the current basic block, go ahead
2283 // and perform the reassociation.
2284 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2285
2286 // First move the selected RHS to the LHS of the root...
2287 Root.setOperand(0, LHSI->getOperand(1));
2288
2289 // Make what used to be the LHS of the root be the user of the root...
2290 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002291 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002292 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2293 return 0;
2294 }
Chris Lattner65725312004-04-16 18:08:07 +00002295 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002296 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002297 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2298 BasicBlock::iterator ARI = &Root; ++ARI;
2299 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2300 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002301
2302 // Now propagate the ExtraOperand down the chain of instructions until we
2303 // get to LHSI.
2304 while (TmpLHSI != LHSI) {
2305 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002306 // Move the instruction to immediately before the chain we are
2307 // constructing to avoid breaking dominance properties.
2308 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2309 BB->getInstList().insert(ARI, NextLHSI);
2310 ARI = NextLHSI;
2311
Chris Lattner564a7272003-08-13 19:01:45 +00002312 Value *NextOp = NextLHSI->getOperand(1);
2313 NextLHSI->setOperand(1, ExtraOperand);
2314 TmpLHSI = NextLHSI;
2315 ExtraOperand = NextOp;
2316 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002317
Chris Lattner564a7272003-08-13 19:01:45 +00002318 // Now that the instructions are reassociated, have the functor perform
2319 // the transformation...
2320 return F.apply(Root);
2321 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002322
Chris Lattner564a7272003-08-13 19:01:45 +00002323 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2324 }
2325 return 0;
2326}
2327
Dan Gohman844731a2008-05-13 00:00:25 +00002328namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002329
2330// AddRHS - Implements: X + X --> X << 1
2331struct AddRHS {
2332 Value *RHS;
2333 AddRHS(Value *rhs) : RHS(rhs) {}
2334 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2335 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002336 return BinaryOperator::CreateShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00002337 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002338 }
2339};
2340
2341// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2342// iff C1&C2 == 0
2343struct AddMaskingAnd {
2344 Constant *C2;
2345 AddMaskingAnd(Constant *c) : C2(c) {}
2346 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002347 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002348 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002349 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002350 }
2351 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002352 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002353 }
2354};
2355
Dan Gohman844731a2008-05-13 00:00:25 +00002356}
2357
Chris Lattner6e7ba452005-01-01 16:22:27 +00002358static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002359 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002360 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002361 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002362 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002363
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002364 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002365 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002366 }
2367
Chris Lattner2eefe512004-04-09 19:05:30 +00002368 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002369 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2370 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002371
Chris Lattner2eefe512004-04-09 19:05:30 +00002372 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2373 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002374 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2375 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002376 }
2377
2378 Value *Op0 = SO, *Op1 = ConstOperand;
2379 if (!ConstIsRHS)
2380 std::swap(Op0, Op1);
2381 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002382 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002383 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002384 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002385 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002386 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002387 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002388 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002389 abort();
2390 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002391 return IC->InsertNewInstBefore(New, I);
2392}
2393
2394// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2395// constant as the other operand, try to fold the binary operator into the
2396// select arguments. This also works for Cast instructions, which obviously do
2397// not have a second operand.
2398static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2399 InstCombiner *IC) {
2400 // Don't modify shared select instructions
2401 if (!SI->hasOneUse()) return 0;
2402 Value *TV = SI->getOperand(1);
2403 Value *FV = SI->getOperand(2);
2404
2405 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002406 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002407 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002408
Chris Lattner6e7ba452005-01-01 16:22:27 +00002409 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2410 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2411
Gabor Greif051a9502008-04-06 20:25:17 +00002412 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2413 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002414 }
2415 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002416}
2417
Chris Lattner4e998b22004-09-29 05:07:12 +00002418
2419/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2420/// node as operand #0, see if we can fold the instruction into the PHI (which
2421/// is only possible if all operands to the PHI are constants).
2422Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2423 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002424 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002425 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002426
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002427 // Check to see if all of the operands of the PHI are constants. If there is
2428 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002429 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002430 BasicBlock *NonConstBB = 0;
2431 for (unsigned i = 0; i != NumPHIValues; ++i)
2432 if (!isa<Constant>(PN->getIncomingValue(i))) {
2433 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002434 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002435 NonConstBB = PN->getIncomingBlock(i);
2436
2437 // If the incoming non-constant value is in I's block, we have an infinite
2438 // loop.
2439 if (NonConstBB == I.getParent())
2440 return 0;
2441 }
2442
2443 // If there is exactly one non-constant value, we can insert a copy of the
2444 // operation in that block. However, if this is a critical edge, we would be
2445 // inserting the computation one some other paths (e.g. inside a loop). Only
2446 // do this if the pred block is unconditionally branching into the phi block.
2447 if (NonConstBB) {
2448 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2449 if (!BI || !BI->isUnconditional()) return 0;
2450 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002451
2452 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002453 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002454 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002455 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002456 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002457
2458 // Next, add all of the operands to the PHI.
2459 if (I.getNumOperands() == 2) {
2460 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002461 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002462 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002464 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2465 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2466 else
2467 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002468 } else {
2469 assert(PN->getIncomingBlock(i) == NonConstBB);
2470 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002472 PN->getIncomingValue(i), C, "phitmp",
2473 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002474 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002475 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002476 CI->getPredicate(),
2477 PN->getIncomingValue(i), C, "phitmp",
2478 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002479 else
2480 assert(0 && "Unknown binop!");
2481
Chris Lattnerdbab3862007-03-02 21:28:56 +00002482 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002483 }
2484 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002485 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002486 } else {
2487 CastInst *CI = cast<CastInst>(&I);
2488 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002489 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002490 Value *InV;
2491 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002492 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002493 } else {
2494 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002495 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002496 I.getType(), "phitmp",
2497 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002498 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002499 }
2500 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002501 }
2502 }
2503 return ReplaceInstUsesWith(I, NewPN);
2504}
2505
Chris Lattner2454a2e2008-01-29 06:52:45 +00002506
2507/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2508/// value is never equal to -0.0.
2509///
2510/// Note that this function will need to be revisited when we support nondefault
2511/// rounding modes!
2512///
2513static bool CannotBeNegativeZero(const Value *V) {
2514 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2515 return !CFP->getValueAPF().isNegZero();
2516
Chris Lattner2454a2e2008-01-29 06:52:45 +00002517 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002518 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002519 if (I->getOpcode() == Instruction::Add &&
2520 isa<ConstantFP>(I->getOperand(1)) &&
2521 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2522 return true;
2523
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002524 // sitofp and uitofp turn into +0.0 for zero.
2525 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2526 return true;
2527
Chris Lattner2454a2e2008-01-29 06:52:45 +00002528 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2529 if (II->getIntrinsicID() == Intrinsic::sqrt)
2530 return CannotBeNegativeZero(II->getOperand(1));
2531
2532 if (const CallInst *CI = dyn_cast<CallInst>(I))
2533 if (const Function *F = CI->getCalledFunction()) {
2534 if (F->isDeclaration()) {
2535 switch (F->getNameLen()) {
2536 case 3: // abs(x) != -0.0
2537 if (!strcmp(F->getNameStart(), "abs")) return true;
2538 break;
2539 case 4: // abs[lf](x) != -0.0
2540 if (!strcmp(F->getNameStart(), "absf")) return true;
2541 if (!strcmp(F->getNameStart(), "absl")) return true;
2542 break;
2543 }
2544 }
2545 }
2546 }
2547
2548 return false;
2549}
2550
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002551/// WillNotOverflowSignedAdd - Return true if we can prove that:
2552/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2553/// This basically requires proving that the add in the original type would not
2554/// overflow to change the sign bit or have a carry out.
2555bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2556 // There are different heuristics we can use for this. Here are some simple
2557 // ones.
2558
2559 // Add has the property that adding any two 2's complement numbers can only
2560 // have one carry bit which can change a sign. As such, if LHS and RHS each
2561 // have at least two sign bits, we know that the addition of the two values will
2562 // sign extend fine.
2563 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2564 return true;
2565
2566
2567 // If one of the operands only has one non-zero bit, and if the other operand
2568 // has a known-zero bit in a more significant place than it (not including the
2569 // sign bit) the ripple may go up to and fill the zero, but won't change the
2570 // sign. For example, (X & ~4) + 1.
2571
2572 // TODO: Implement.
2573
2574 return false;
2575}
2576
Chris Lattner2454a2e2008-01-29 06:52:45 +00002577
Chris Lattner7e708292002-06-25 16:13:24 +00002578Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002579 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002580 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002581
Chris Lattner66331a42004-04-10 22:01:55 +00002582 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002583 // X + undef -> undef
2584 if (isa<UndefValue>(RHS))
2585 return ReplaceInstUsesWith(I, RHS);
2586
Chris Lattner66331a42004-04-10 22:01:55 +00002587 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002588 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002589 if (RHSC->isNullValue())
2590 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002591 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002592 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2593 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002594 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002595 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002596
Chris Lattner66331a42004-04-10 22:01:55 +00002597 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002598 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002599 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002600 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002601 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002602 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002603
2604 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2605 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002606 if (!isa<VectorType>(I.getType())) {
2607 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2608 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2609 KnownZero, KnownOne))
2610 return &I;
2611 }
Chris Lattner66331a42004-04-10 22:01:55 +00002612 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002613
2614 if (isa<PHINode>(LHS))
2615 if (Instruction *NV = FoldOpIntoPhi(I))
2616 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002617
Chris Lattner4f637d42006-01-06 17:59:59 +00002618 ConstantInt *XorRHS = 0;
2619 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002620 if (isa<ConstantInt>(RHSC) &&
2621 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002622 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002623 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002624
Zhou Sheng4351c642007-04-02 08:20:41 +00002625 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002626 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2627 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002628 do {
2629 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002630 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2631 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002632 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2633 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002634 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002635 if (!MaskedValueIsZero(XorLHS,
2636 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002637 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002638 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002639 }
2640 }
2641 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002642 C0080Val = APIntOps::lshr(C0080Val, Size);
2643 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2644 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002645
Reid Spencer35c38852007-03-28 01:36:16 +00002646 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002647 // with funny bit widths then this switch statement should be removed. It
2648 // is just here to get the size of the "middle" type back up to something
2649 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002650 const Type *MiddleType = 0;
2651 switch (Size) {
2652 default: break;
2653 case 32: MiddleType = Type::Int32Ty; break;
2654 case 16: MiddleType = Type::Int16Ty; break;
2655 case 8: MiddleType = Type::Int8Ty; break;
2656 }
2657 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002658 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002659 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002660 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002661 }
2662 }
Chris Lattner66331a42004-04-10 22:01:55 +00002663 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002664
Chris Lattner564a7272003-08-13 19:01:45 +00002665 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002666 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002667 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002668
2669 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2670 if (RHSI->getOpcode() == Instruction::Sub)
2671 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2672 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2673 }
2674 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2675 if (LHSI->getOpcode() == Instruction::Sub)
2676 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2677 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2678 }
Robert Bocchino71698282004-07-27 21:02:21 +00002679 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002680
Chris Lattner5c4afb92002-05-08 22:46:53 +00002681 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002682 // -A + -B --> -(A + B)
2683 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002684 if (LHS->getType()->isIntOrIntVector()) {
2685 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002686 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002687 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002688 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002689 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002690 }
2691
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002692 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002693 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002694
2695 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002696 if (!isa<Constant>(RHS))
2697 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002698 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002699
Misha Brukmanfd939082005-04-21 23:48:37 +00002700
Chris Lattner50af16a2004-11-13 19:50:12 +00002701 ConstantInt *C2;
2702 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2703 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002704 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002705
2706 // X*C1 + X*C2 --> X * (C1+C2)
2707 ConstantInt *C1;
2708 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002709 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002710 }
2711
2712 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002713 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002714 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002715
Chris Lattnere617c9e2007-01-05 02:17:46 +00002716 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002717 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2718 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002719
Chris Lattnerad3448c2003-02-18 19:57:07 +00002720
Chris Lattner564a7272003-08-13 19:01:45 +00002721 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002722 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002723 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2724 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002725
2726 // A+B --> A|B iff A and B have no bits set in common.
2727 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2728 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2729 APInt LHSKnownOne(IT->getBitWidth(), 0);
2730 APInt LHSKnownZero(IT->getBitWidth(), 0);
2731 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2732 if (LHSKnownZero != 0) {
2733 APInt RHSKnownOne(IT->getBitWidth(), 0);
2734 APInt RHSKnownZero(IT->getBitWidth(), 0);
2735 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2736
2737 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002738 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002739 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002740 }
2741 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002742
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002743 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002744 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002745 Value *W, *X, *Y, *Z;
2746 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2747 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2748 if (W != Y) {
2749 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002750 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002751 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002752 std::swap(W, X);
2753 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002754 std::swap(Y, Z);
2755 std::swap(W, X);
2756 }
2757 }
2758
2759 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002761 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002762 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002763 }
2764 }
2765 }
2766
Chris Lattner6b032052003-10-02 15:11:26 +00002767 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002768 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002769 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002770 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002771
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002772 // (X & FF00) + xx00 -> (X+xx00) & FF00
2773 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002774 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002775 if (Anded == CRHS) {
2776 // See if all bits from the first bit set in the Add RHS up are included
2777 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002778 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002779
2780 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002781 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002782
2783 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002784 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002785
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002786 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2787 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002788 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002789 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002790 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002791 }
2792 }
2793 }
2794
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002795 // Try to fold constant add into select arguments.
2796 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002797 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002798 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002799 }
2800
Reid Spencer1628cec2006-10-26 06:15:43 +00002801 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002802 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002803 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002804 CastInst *CI = dyn_cast<CastInst>(LHS);
2805 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002806 if (!CI) {
2807 CI = dyn_cast<CastInst>(RHS);
2808 Other = LHS;
2809 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002810 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002811 (CI->getType()->getPrimitiveSizeInBits() ==
2812 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002813 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002814 unsigned AS =
2815 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002816 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2817 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002818 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002819 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002820 }
2821 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002822
Chris Lattner42790482007-12-20 01:56:58 +00002823 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002824 {
2825 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2826 Value *Other = RHS;
2827 if (!SI) {
2828 SI = dyn_cast<SelectInst>(RHS);
2829 Other = LHS;
2830 }
Chris Lattner42790482007-12-20 01:56:58 +00002831 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002832 Value *TV = SI->getTrueValue();
2833 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002834 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002835
2836 // Can we fold the add into the argument of the select?
2837 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002838 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2839 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002840 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002841 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2842 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002843 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002844 }
2845 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002846
2847 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2848 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2849 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2850 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002851
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002852 // Check for (add (sext x), y), see if we can merge this into an
2853 // integer add followed by a sext.
2854 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2855 // (add (sext x), cst) --> (sext (add x, cst'))
2856 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2857 Constant *CI =
2858 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2859 if (LHSConv->hasOneUse() &&
2860 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2861 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2862 // Insert the new, smaller add.
2863 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2864 CI, "addconv");
2865 InsertNewInstBefore(NewAdd, I);
2866 return new SExtInst(NewAdd, I.getType());
2867 }
2868 }
2869
2870 // (add (sext x), (sext y)) --> (sext (add int x, y))
2871 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2872 // Only do this if x/y have the same type, if at last one of them has a
2873 // single use (so we don't increase the number of sexts), and if the
2874 // integer add will not overflow.
2875 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2876 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2877 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2878 RHSConv->getOperand(0))) {
2879 // Insert the new integer add.
2880 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2881 RHSConv->getOperand(0),
2882 "addconv");
2883 InsertNewInstBefore(NewAdd, I);
2884 return new SExtInst(NewAdd, I.getType());
2885 }
2886 }
2887 }
2888
2889 // Check for (add double (sitofp x), y), see if we can merge this into an
2890 // integer add followed by a promotion.
2891 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2892 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2893 // ... if the constant fits in the integer value. This is useful for things
2894 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2895 // requires a constant pool load, and generally allows the add to be better
2896 // instcombined.
2897 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2898 Constant *CI =
2899 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2900 if (LHSConv->hasOneUse() &&
2901 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2902 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2903 // Insert the new integer add.
2904 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2905 CI, "addconv");
2906 InsertNewInstBefore(NewAdd, I);
2907 return new SIToFPInst(NewAdd, I.getType());
2908 }
2909 }
2910
2911 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2912 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2913 // Only do this if x/y have the same type, if at last one of them has a
2914 // single use (so we don't increase the number of int->fp conversions),
2915 // and if the integer add will not overflow.
2916 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2917 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2918 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2919 RHSConv->getOperand(0))) {
2920 // Insert the new integer add.
2921 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2922 RHSConv->getOperand(0),
2923 "addconv");
2924 InsertNewInstBefore(NewAdd, I);
2925 return new SIToFPInst(NewAdd, I.getType());
2926 }
2927 }
2928 }
2929
Chris Lattner7e708292002-06-25 16:13:24 +00002930 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002931}
2932
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002933// isSignBit - Return true if the value represented by the constant only has the
2934// highest order bit set.
2935static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002936 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002937 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002938}
2939
Chris Lattner7e708292002-06-25 16:13:24 +00002940Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002942
Chris Lattner233f7dc2002-08-12 21:17:25 +00002943 if (Op0 == Op1) // sub X, X -> 0
2944 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002945
Chris Lattner233f7dc2002-08-12 21:17:25 +00002946 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002947 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002948 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002949
Chris Lattnere87597f2004-10-16 18:11:37 +00002950 if (isa<UndefValue>(Op0))
2951 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2952 if (isa<UndefValue>(Op1))
2953 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2954
Chris Lattnerd65460f2003-11-05 01:06:05 +00002955 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2956 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002957 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002958 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002959
Chris Lattnerd65460f2003-11-05 01:06:05 +00002960 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002961 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002962 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002963 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002964
Chris Lattner76b7a062007-01-15 07:02:54 +00002965 // -(X >>u 31) -> (X >>s 31)
2966 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002967 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002968 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002969 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002970 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002971 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002972 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002973 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002974 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002975 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002976 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002977 }
2978 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002979 }
2980 else if (SI->getOpcode() == Instruction::AShr) {
2981 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2982 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002983 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002984 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002985 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002986 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002987 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002988 }
2989 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002990 }
2991 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002992 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002993
2994 // Try to fold constant sub into select arguments.
2995 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002996 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002997 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002998
2999 if (isa<PHINode>(Op0))
3000 if (Instruction *NV = FoldOpIntoPhi(I))
3001 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00003002 }
3003
Chris Lattner43d84d62005-04-07 16:15:25 +00003004 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3005 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00003006 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00003007 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003008 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00003009 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003010 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00003011 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
3012 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
3013 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003014 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00003015 Op1I->getOperand(0));
3016 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003017 }
3018
Chris Lattnerfd059242003-10-15 16:48:29 +00003019 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00003020 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
3021 // is not used by anyone else...
3022 //
Chris Lattner0517e722004-02-02 20:09:56 +00003023 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00003024 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00003025 // Swap the two operands of the subexpr...
3026 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
3027 Op1I->setOperand(0, IIOp1);
3028 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003029
Chris Lattnera2881962003-02-18 19:28:33 +00003030 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003031 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003032 }
3033
3034 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3035 //
3036 if (Op1I->getOpcode() == Instruction::And &&
3037 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3038 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3039
Chris Lattnerf523d062004-06-09 05:08:07 +00003040 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003041 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3042 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003043 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003044
Reid Spencerac5209e2006-10-16 23:08:08 +00003045 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003046 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003047 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003048 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003049 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003050 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003051 ConstantExpr::getNeg(DivRHS));
3052
Chris Lattnerad3448c2003-02-18 19:57:07 +00003053 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003054 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003055 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003056 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003057 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003058 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003059
3060 // X - ((X / Y) * Y) --> X % Y
3061 if (Op1I->getOpcode() == Instruction::Mul)
3062 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3063 if (Op0 == I->getOperand(0) &&
3064 Op1I->getOperand(1) == I->getOperand(1)) {
3065 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003066 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003067 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003068 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003069 }
Chris Lattner40371712002-05-09 01:29:19 +00003070 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003071 }
Chris Lattnera2881962003-02-18 19:28:33 +00003072
Chris Lattner9919e3d2006-12-02 00:13:08 +00003073 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003074 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003075 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003076 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3077 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3078 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3079 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003080 } else if (Op0I->getOpcode() == Instruction::Sub) {
3081 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003082 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003083 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003084 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003085
Chris Lattner50af16a2004-11-13 19:50:12 +00003086 ConstantInt *C1;
3087 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003088 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003089 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003090
Chris Lattner50af16a2004-11-13 19:50:12 +00003091 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3092 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003093 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003094 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003095 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003096}
3097
Chris Lattnera0141b92007-07-15 20:42:37 +00003098/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3099/// comparison only checks the sign bit. If it only checks the sign bit, set
3100/// TrueIfSigned if the result of the comparison is true when the input value is
3101/// signed.
3102static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3103 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003104 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003105 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3106 TrueIfSigned = true;
3107 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003108 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3109 TrueIfSigned = true;
3110 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003111 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3112 TrueIfSigned = false;
3113 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003114 case ICmpInst::ICMP_UGT:
3115 // True if LHS u> RHS and RHS == high-bit-mask - 1
3116 TrueIfSigned = true;
3117 return RHS->getValue() ==
3118 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3119 case ICmpInst::ICMP_UGE:
3120 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3121 TrueIfSigned = true;
3122 return RHS->getValue() ==
3123 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003124 default:
3125 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003126 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003127}
3128
Chris Lattner7e708292002-06-25 16:13:24 +00003129Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003130 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003131 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003132
Chris Lattnere87597f2004-10-16 18:11:37 +00003133 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3134 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3135
Chris Lattner233f7dc2002-08-12 21:17:25 +00003136 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003137 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003139
3140 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003141 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003142 if (SI->getOpcode() == Instruction::Shl)
3143 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003144 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003145 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003146
Zhou Sheng843f07672007-04-19 05:39:12 +00003147 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003148 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3149 if (CI->equalsInt(1)) // X * 1 == X
3150 return ReplaceInstUsesWith(I, Op0);
3151 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003152 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003153
Zhou Sheng97b52c22007-03-29 01:57:21 +00003154 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003155 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003156 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003157 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003158 }
Robert Bocchino71698282004-07-27 21:02:21 +00003159 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003160 if (Op1F->isNullValue())
3161 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003162
Chris Lattnera2881962003-02-18 19:28:33 +00003163 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3164 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003165 // We need a better interface for long double here.
3166 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3167 if (Op1F->isExactlyValue(1.0))
3168 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003169 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003170
3171 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3172 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003173 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003174 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003175 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003176 Op1, "tmp");
3177 InsertNewInstBefore(Add, I);
3178 Value *C1C2 = ConstantExpr::getMul(Op1,
3179 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003180 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003181
3182 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003183
3184 // Try to fold constant mul into select arguments.
3185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003187 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003188
3189 if (isa<PHINode>(Op0))
3190 if (Instruction *NV = FoldOpIntoPhi(I))
3191 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003192 }
3193
Chris Lattnera4f445b2003-03-10 23:23:04 +00003194 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3195 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003196 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003197
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003198 // If one of the operands of the multiply is a cast from a boolean value, then
3199 // we know the bool is either zero or one, so this is a 'masking' multiply.
3200 // See if we can simplify things based on how the boolean was originally
3201 // formed.
3202 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003203 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003204 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003205 BoolCast = CI;
3206 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003207 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003208 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003209 BoolCast = CI;
3210 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003211 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003212 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3213 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003214 bool TIS = false;
3215
Reid Spencere4d87aa2006-12-23 06:05:41 +00003216 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003217 // multiply into a shift/and combination.
3218 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003219 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3220 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003221 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003222 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003223 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003224 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003225 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003226 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003227 BoolCast->getOperand(0)->getName()+
3228 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003229
3230 // If the multiply type is not the same as the source type, sign extend
3231 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003232 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003233 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3234 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003235 Instruction::CastOps opcode =
3236 (SrcBits == DstBits ? Instruction::BitCast :
3237 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3238 V = InsertCastBefore(opcode, V, I.getType(), I);
3239 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003240
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003241 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003242 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003243 }
3244 }
3245 }
3246
Chris Lattner7e708292002-06-25 16:13:24 +00003247 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003248}
3249
Reid Spencer1628cec2006-10-26 06:15:43 +00003250/// This function implements the transforms on div instructions that work
3251/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3252/// used by the visitors to those instructions.
3253/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003254Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003256
Chris Lattner50b2ca42008-02-19 06:12:18 +00003257 // undef / X -> 0 for integer.
3258 // undef / X -> undef for FP (the undef could be a snan).
3259 if (isa<UndefValue>(Op0)) {
3260 if (Op0->getType()->isFPOrFPVector())
3261 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003262 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003263 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003264
3265 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003266 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003267 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003268
Chris Lattner25feae52008-01-28 00:58:18 +00003269 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3270 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003271 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003272 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3273 // the same basic block, then we replace the select with Y, and the
3274 // condition of the select with false (if the cond value is in the same BB).
3275 // If the select has uses other than the div, this allows them to be
3276 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3277 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003278 if (ST->isNullValue()) {
3279 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3280 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003281 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003282 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3283 I.setOperand(1, SI->getOperand(2));
3284 else
3285 UpdateValueUsesWith(SI, SI->getOperand(2));
3286 return &I;
3287 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003288
Chris Lattner25feae52008-01-28 00:58:18 +00003289 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3290 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003291 if (ST->isNullValue()) {
3292 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3293 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003294 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003295 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3296 I.setOperand(1, SI->getOperand(1));
3297 else
3298 UpdateValueUsesWith(SI, SI->getOperand(1));
3299 return &I;
3300 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003301 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003302
Reid Spencer1628cec2006-10-26 06:15:43 +00003303 return 0;
3304}
Misha Brukmanfd939082005-04-21 23:48:37 +00003305
Reid Spencer1628cec2006-10-26 06:15:43 +00003306/// This function implements the transforms common to both integer division
3307/// instructions (udiv and sdiv). It is called by the visitors to those integer
3308/// division instructions.
3309/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003310Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3312
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003313 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3314 if (Op0 == Op1)
3315 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3316
Reid Spencer1628cec2006-10-26 06:15:43 +00003317 if (Instruction *Common = commonDivTransforms(I))
3318 return Common;
3319
3320 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3321 // div X, 1 == X
3322 if (RHS->equalsInt(1))
3323 return ReplaceInstUsesWith(I, Op0);
3324
3325 // (X / C1) / C2 -> X / (C1*C2)
3326 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3327 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3328 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003329 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3330 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3331 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003332 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003333 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003334 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003335
Reid Spencerbca0e382007-03-23 20:05:17 +00003336 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003337 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3338 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3339 return R;
3340 if (isa<PHINode>(Op0))
3341 if (Instruction *NV = FoldOpIntoPhi(I))
3342 return NV;
3343 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003344 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003345
Chris Lattnera2881962003-02-18 19:28:33 +00003346 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003347 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003348 if (LHS->equalsInt(0))
3349 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3350
Reid Spencer1628cec2006-10-26 06:15:43 +00003351 return 0;
3352}
3353
3354Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3356
3357 // Handle the integer div common cases
3358 if (Instruction *Common = commonIDivTransforms(I))
3359 return Common;
3360
3361 // X udiv C^2 -> X >> C
3362 // Check to see if this is an unsigned division with an exact power of 2,
3363 // if so, convert to a right shift.
3364 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003365 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003366 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003367 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003368 }
3369
3370 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003371 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003372 if (RHSI->getOpcode() == Instruction::Shl &&
3373 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003374 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003375 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003376 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003377 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003378 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003379 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003380 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003381 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003382 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003383 }
3384 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003385 }
3386
Reid Spencer1628cec2006-10-26 06:15:43 +00003387 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3388 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003389 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003390 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003391 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003392 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003393 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003394 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003395 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003396 // Construct the "on true" case of the select
3397 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003398 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003399 Op0, TC, SI->getName()+".t");
3400 TSI = InsertNewInstBefore(TSI, I);
3401
3402 // Construct the "on false" case of the select
3403 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003404 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003405 Op0, FC, SI->getName()+".f");
3406 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003407
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003408 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003409 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003410 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003411 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003412 return 0;
3413}
3414
Reid Spencer1628cec2006-10-26 06:15:43 +00003415Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3417
3418 // Handle the integer div common cases
3419 if (Instruction *Common = commonIDivTransforms(I))
3420 return Common;
3421
3422 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3423 // sdiv X, -1 == -X
3424 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003425 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003426
3427 // -X/C -> X/-C
3428 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003429 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003430 }
3431
3432 // If the sign bits of both operands are zero (i.e. we can prove they are
3433 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003434 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003435 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003436 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003437 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003438 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003439 }
3440 }
3441
3442 return 0;
3443}
3444
3445Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3446 return commonDivTransforms(I);
3447}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003448
Reid Spencer0a783f72006-11-02 01:53:59 +00003449/// This function implements the transforms on rem instructions that work
3450/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3451/// is used by the visitors to those instructions.
3452/// @brief Transforms common to all three rem instructions
3453Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003454 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003455
Chris Lattner50b2ca42008-02-19 06:12:18 +00003456 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003457 if (Constant *LHS = dyn_cast<Constant>(Op0))
3458 if (LHS->isNullValue())
3459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3460
Chris Lattner50b2ca42008-02-19 06:12:18 +00003461 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3462 if (I.getType()->isFPOrFPVector())
3463 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003465 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003466 if (isa<UndefValue>(Op1))
3467 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003468
3469 // Handle cases involving: rem X, (select Cond, Y, Z)
3470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3471 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3472 // the same basic block, then we replace the select with Y, and the
3473 // condition of the select with false (if the cond value is in the same
3474 // BB). If the select has uses other than the div, this allows them to be
3475 // simplified also.
3476 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3477 if (ST->isNullValue()) {
3478 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3479 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003480 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003481 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3482 I.setOperand(1, SI->getOperand(2));
3483 else
3484 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003485 return &I;
3486 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003487 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3488 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3489 if (ST->isNullValue()) {
3490 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3491 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003492 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003493 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3494 I.setOperand(1, SI->getOperand(1));
3495 else
3496 UpdateValueUsesWith(SI, SI->getOperand(1));
3497 return &I;
3498 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003499 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003500
Reid Spencer0a783f72006-11-02 01:53:59 +00003501 return 0;
3502}
3503
3504/// This function implements the transforms common to both integer remainder
3505/// instructions (urem and srem). It is called by the visitors to those integer
3506/// remainder instructions.
3507/// @brief Common integer remainder transforms
3508Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3510
3511 if (Instruction *common = commonRemTransforms(I))
3512 return common;
3513
Chris Lattner857e8cd2004-12-12 21:48:58 +00003514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003515 // X % 0 == undef, we don't need to preserve faults!
3516 if (RHS->equalsInt(0))
3517 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3518
Chris Lattnera2881962003-02-18 19:28:33 +00003519 if (RHS->equalsInt(1)) // X % 1 == 0
3520 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3521
Chris Lattner97943922006-02-28 05:49:21 +00003522 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3523 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3524 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3525 return R;
3526 } else if (isa<PHINode>(Op0I)) {
3527 if (Instruction *NV = FoldOpIntoPhi(I))
3528 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003529 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003530
3531 // See if we can fold away this rem instruction.
3532 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3533 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3534 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3535 KnownZero, KnownOne))
3536 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003537 }
Chris Lattnera2881962003-02-18 19:28:33 +00003538 }
3539
Reid Spencer0a783f72006-11-02 01:53:59 +00003540 return 0;
3541}
3542
3543Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3544 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3545
3546 if (Instruction *common = commonIRemTransforms(I))
3547 return common;
3548
3549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3550 // X urem C^2 -> X and C
3551 // Check to see if this is an unsigned remainder with an exact power of 2,
3552 // if so, convert to a bitwise and.
3553 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003554 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003555 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003556 }
3557
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003558 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003559 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3560 if (RHSI->getOpcode() == Instruction::Shl &&
3561 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003562 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003563 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003564 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003565 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003566 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003567 }
3568 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003569 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003570
Reid Spencer0a783f72006-11-02 01:53:59 +00003571 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3572 // where C1&C2 are powers of two.
3573 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3574 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3575 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3576 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003577 if ((STO->getValue().isPowerOf2()) &&
3578 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003579 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003580 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003581 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003582 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003583 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003584 }
3585 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003586 }
3587
Chris Lattner3f5b8772002-05-06 16:14:14 +00003588 return 0;
3589}
3590
Reid Spencer0a783f72006-11-02 01:53:59 +00003591Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3593
Dan Gohmancff55092007-11-05 23:16:33 +00003594 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003595 if (Instruction *common = commonIRemTransforms(I))
3596 return common;
3597
3598 if (Value *RHSNeg = dyn_castNegVal(Op1))
3599 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003600 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003601 // X % -Y -> X % Y
3602 AddUsesToWorkList(I);
3603 I.setOperand(1, RHSNeg);
3604 return &I;
3605 }
3606
Dan Gohmancff55092007-11-05 23:16:33 +00003607 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003608 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003609 if (I.getType()->isInteger()) {
3610 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3611 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3612 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003613 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003614 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003615 }
3616
3617 return 0;
3618}
3619
3620Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003621 return commonRemTransforms(I);
3622}
3623
Chris Lattner8b170942002-08-09 23:47:40 +00003624// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003626 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003627 if (!isSigned)
3628 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3629 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003630}
3631
3632// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003633static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003634 if (!isSigned)
3635 return C->getValue() == 1; // unsigned
3636
3637 // Calculate 1111111111000000000000
3638 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3639 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003640}
3641
Chris Lattner457dd822004-06-09 07:59:58 +00003642// isOneBitSet - Return true if there is exactly one bit set in the specified
3643// constant.
3644static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003645 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003646}
3647
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003648// isHighOnes - Return true if the constant is of the form 1+0+.
3649// This is the same as lowones(~X).
3650static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003651 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003652}
3653
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003655/// are carefully arranged to allow folding of expressions such as:
3656///
3657/// (A < B) | (A > B) --> (A != B)
3658///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003659/// Note that this is only valid if the first and second predicates have the
3660/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003661///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003662/// Three bits are used to represent the condition, as follows:
3663/// 0 A > B
3664/// 1 A == B
3665/// 2 A < B
3666///
3667/// <=> Value Definition
3668/// 000 0 Always false
3669/// 001 1 A > B
3670/// 010 2 A == B
3671/// 011 3 A >= B
3672/// 100 4 A < B
3673/// 101 5 A != B
3674/// 110 6 A <= B
3675/// 111 7 Always true
3676///
3677static unsigned getICmpCode(const ICmpInst *ICI) {
3678 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003679 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003680 case ICmpInst::ICMP_UGT: return 1; // 001
3681 case ICmpInst::ICMP_SGT: return 1; // 001
3682 case ICmpInst::ICMP_EQ: return 2; // 010
3683 case ICmpInst::ICMP_UGE: return 3; // 011
3684 case ICmpInst::ICMP_SGE: return 3; // 011
3685 case ICmpInst::ICMP_ULT: return 4; // 100
3686 case ICmpInst::ICMP_SLT: return 4; // 100
3687 case ICmpInst::ICMP_NE: return 5; // 101
3688 case ICmpInst::ICMP_ULE: return 6; // 110
3689 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003690 // True -> 7
3691 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003692 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003693 return 0;
3694 }
3695}
3696
Reid Spencere4d87aa2006-12-23 06:05:41 +00003697/// getICmpValue - This is the complement of getICmpCode, which turns an
3698/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003699/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003700/// of predicate to use in new icmp instructions.
3701static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3702 switch (code) {
3703 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003704 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003705 case 1:
3706 if (sign)
3707 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3708 else
3709 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3710 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3711 case 3:
3712 if (sign)
3713 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3714 else
3715 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3716 case 4:
3717 if (sign)
3718 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3719 else
3720 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3721 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3722 case 6:
3723 if (sign)
3724 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3725 else
3726 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003727 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003728 }
3729}
3730
Reid Spencere4d87aa2006-12-23 06:05:41 +00003731static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3732 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3733 (ICmpInst::isSignedPredicate(p1) &&
3734 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3735 (ICmpInst::isSignedPredicate(p2) &&
3736 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3737}
3738
3739namespace {
3740// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3741struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003742 InstCombiner &IC;
3743 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003744 ICmpInst::Predicate pred;
3745 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3746 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3747 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003748 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003749 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3750 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003751 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3752 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003753 return false;
3754 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 Instruction *apply(Instruction &Log) const {
3756 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3757 if (ICI->getOperand(0) != LHS) {
3758 assert(ICI->getOperand(1) == LHS);
3759 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003760 }
3761
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003762 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003763 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003764 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003765 unsigned Code;
3766 switch (Log.getOpcode()) {
3767 case Instruction::And: Code = LHSCode & RHSCode; break;
3768 case Instruction::Or: Code = LHSCode | RHSCode; break;
3769 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003770 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003771 }
3772
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003773 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3774 ICmpInst::isSignedPredicate(ICI->getPredicate());
3775
3776 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003777 if (Instruction *I = dyn_cast<Instruction>(RV))
3778 return I;
3779 // Otherwise, it's a constant boolean value...
3780 return IC.ReplaceInstUsesWith(Log, RV);
3781 }
3782};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003783} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003784
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003785// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3786// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003787// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003788Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003789 ConstantInt *OpRHS,
3790 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003791 BinaryOperator &TheAnd) {
3792 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003793 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003794 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003795 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003796
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003797 switch (Op->getOpcode()) {
3798 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003799 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003800 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003801 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003802 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003803 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003804 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003805 }
3806 break;
3807 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003808 if (Together == AndRHS) // (X | C) & C --> C
3809 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003810
Chris Lattner6e7ba452005-01-01 16:22:27 +00003811 if (Op->hasOneUse() && Together != OpRHS) {
3812 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003813 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003814 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003815 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003816 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003817 }
3818 break;
3819 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003820 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003821 // Adding a one to a single bit bit-field should be turned into an XOR
3822 // of the bit. First thing to check is to see if this AND is with a
3823 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003824 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003825
3826 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003827 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003828 // Ok, at this point, we know that we are masking the result of the
3829 // ADD down to exactly one bit. If the constant we are adding has
3830 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003831 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003832
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003833 // Check to see if any bits below the one bit set in AndRHSV are set.
3834 if ((AddRHS & (AndRHSV-1)) == 0) {
3835 // If not, the only thing that can effect the output of the AND is
3836 // the bit specified by AndRHSV. If that bit is set, the effect of
3837 // the XOR is to toggle the bit. If it is clear, then the ADD has
3838 // no effect.
3839 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3840 TheAnd.setOperand(0, X);
3841 return &TheAnd;
3842 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003843 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003844 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003845 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003846 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003847 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003848 }
3849 }
3850 }
3851 }
3852 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003853
3854 case Instruction::Shl: {
3855 // We know that the AND will not produce any of the bits shifted in, so if
3856 // the anded constant includes them, clear them now!
3857 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003858 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003859 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003860 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3861 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003862
Zhou Sheng290bec52007-03-29 08:15:12 +00003863 if (CI->getValue() == ShlMask) {
3864 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003865 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3866 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003867 TheAnd.setOperand(1, CI);
3868 return &TheAnd;
3869 }
3870 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003871 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003872 case Instruction::LShr:
3873 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003874 // We know that the AND will not produce any of the bits shifted in, so if
3875 // the anded constant includes them, clear them now! This only applies to
3876 // unsigned shifts, because a signed shr may bring in set bits!
3877 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003878 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003879 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003880 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3881 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003882
Zhou Sheng290bec52007-03-29 08:15:12 +00003883 if (CI->getValue() == ShrMask) {
3884 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003885 return ReplaceInstUsesWith(TheAnd, Op);
3886 } else if (CI != AndRHS) {
3887 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3888 return &TheAnd;
3889 }
3890 break;
3891 }
3892 case Instruction::AShr:
3893 // Signed shr.
3894 // See if this is shifting in some sign extension, then masking it out
3895 // with an and.
3896 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003897 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003898 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003899 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3900 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003901 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003902 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003903 // Make the argument unsigned.
3904 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003905 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003906 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003907 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003908 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003909 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003910 }
3911 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003912 }
3913 return 0;
3914}
3915
Chris Lattner8b170942002-08-09 23:47:40 +00003916
Chris Lattnera96879a2004-09-29 17:40:11 +00003917/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3918/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003919/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3920/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003921/// insert new instructions.
3922Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003923 bool isSigned, bool Inside,
3924 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003925 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003926 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003927 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003928
Chris Lattnera96879a2004-09-29 17:40:11 +00003929 if (Inside) {
3930 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003931 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003932
Reid Spencere4d87aa2006-12-23 06:05:41 +00003933 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003934 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003935 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003936 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3937 return new ICmpInst(pred, V, Hi);
3938 }
3939
3940 // Emit V-Lo <u Hi-Lo
3941 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003942 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003943 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003944 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3945 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003946 }
3947
3948 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003949 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003950
Reid Spencere4e40032007-03-21 23:19:50 +00003951 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003952 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003953 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003954 ICmpInst::Predicate pred = (isSigned ?
3955 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3956 return new ICmpInst(pred, V, Hi);
3957 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003958
Reid Spencere4e40032007-03-21 23:19:50 +00003959 // Emit V-Lo >u Hi-1-Lo
3960 // Note that Hi has already had one subtracted from it, above.
3961 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003962 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003963 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003964 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3965 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003966}
3967
Chris Lattner7203e152005-09-18 07:22:02 +00003968// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3969// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3970// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3971// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003972static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003973 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003974 uint32_t BitWidth = Val->getType()->getBitWidth();
3975 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003976
3977 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003978 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003979 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003980 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003981 return true;
3982}
3983
Chris Lattner7203e152005-09-18 07:22:02 +00003984/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3985/// where isSub determines whether the operator is a sub. If we can fold one of
3986/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003987///
3988/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3989/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3990/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3991///
3992/// return (A +/- B).
3993///
3994Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003995 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003996 Instruction &I) {
3997 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3998 if (!LHSI || LHSI->getNumOperands() != 2 ||
3999 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4000
4001 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4002
4003 switch (LHSI->getOpcode()) {
4004 default: return 0;
4005 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00004006 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004007 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004008 if ((Mask->getValue().countLeadingZeros() +
4009 Mask->getValue().countPopulation()) ==
4010 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004011 break;
4012
4013 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4014 // part, we don't need any explicit masks to take them out of A. If that
4015 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004016 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004017 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004018 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004019 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004020 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004021 break;
4022 }
4023 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004024 return 0;
4025 case Instruction::Or:
4026 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004027 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004028 if ((Mask->getValue().countLeadingZeros() +
4029 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004030 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004031 break;
4032 return 0;
4033 }
4034
4035 Instruction *New;
4036 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004037 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004038 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004039 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004040 return InsertNewInstBefore(New, I);
4041}
4042
Chris Lattner7e708292002-06-25 16:13:24 +00004043Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004044 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004045 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004046
Chris Lattnere87597f2004-10-16 18:11:37 +00004047 if (isa<UndefValue>(Op1)) // X & undef -> 0
4048 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4049
Chris Lattner6e7ba452005-01-01 16:22:27 +00004050 // and X, X = X
4051 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004052 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004053
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004054 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004055 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004056 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004057 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4058 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4059 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004060 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004061 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004062 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004063 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004064 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004065 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004066 } else if (isa<ConstantAggregateZero>(Op1)) {
4067 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004068 }
4069 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004070
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004071 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004072 const APInt& AndRHSMask = AndRHS->getValue();
4073 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004074
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004075 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004076 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004077 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004078 Value *Op0LHS = Op0I->getOperand(0);
4079 Value *Op0RHS = Op0I->getOperand(1);
4080 switch (Op0I->getOpcode()) {
4081 case Instruction::Xor:
4082 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004083 // If the mask is only needed on one incoming arm, push it up.
4084 if (Op0I->hasOneUse()) {
4085 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4086 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004087 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004088 Op0RHS->getName()+".masked");
4089 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004091 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004092 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004093 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004094 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4095 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004096 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004097 Op0LHS->getName()+".masked");
4098 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004099 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004100 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4101 }
4102 }
4103
Chris Lattner6e7ba452005-01-01 16:22:27 +00004104 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004105 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004106 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4107 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4108 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4109 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004110 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004111 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004112 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004113 break;
4114
4115 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004116 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4117 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4118 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4119 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004120 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004121 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004122 }
4123
Chris Lattner58403262003-07-23 19:25:52 +00004124 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004125 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004126 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004127 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004128 // If this is an integer truncation or change from signed-to-unsigned, and
4129 // if the source is an and/or with immediate, transform it. This
4130 // frequently occurs for bitfield accesses.
4131 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004132 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004133 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004134 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004135 if (CastOp->getOpcode() == Instruction::And) {
4136 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004137 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4138 // This will fold the two constants together, which may allow
4139 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004140 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004141 CastOp->getOperand(0), I.getType(),
4142 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004143 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004144 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004145 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004146 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004147 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004148 } else if (CastOp->getOpcode() == Instruction::Or) {
4149 // Change: and (cast (or X, C1) to T), C2
4150 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004151 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004152 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4153 return ReplaceInstUsesWith(I, AndRHS);
4154 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004155 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004156 }
Chris Lattner06782f82003-07-23 19:36:21 +00004157 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004158
4159 // Try to fold constant and into select arguments.
4160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004162 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004163 if (isa<PHINode>(Op0))
4164 if (Instruction *NV = FoldOpIntoPhi(I))
4165 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004166 }
4167
Chris Lattner8d969642003-03-10 23:06:50 +00004168 Value *Op0NotVal = dyn_castNotVal(Op0);
4169 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004170
Chris Lattner5b62aa72004-06-18 06:07:51 +00004171 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4172 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4173
Misha Brukmancb6267b2004-07-30 12:50:08 +00004174 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004175 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004176 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004177 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004178 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004179 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004180 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004181
4182 {
Chris Lattner003b6202007-06-15 05:58:24 +00004183 Value *A = 0, *B = 0, *C = 0, *D = 0;
4184 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004185 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4186 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004187
4188 // (A|B) & ~(A&B) -> A^B
4189 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4190 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004191 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004192 }
4193 }
4194
4195 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004196 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4197 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004198
4199 // ~(A&B) & (A|B) -> A^B
4200 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4201 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004202 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004203 }
4204 }
Chris Lattner64daab52006-04-01 08:03:55 +00004205
4206 if (Op0->hasOneUse() &&
4207 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4208 if (A == Op1) { // (A^B)&A -> A&(A^B)
4209 I.swapOperands(); // Simplify below
4210 std::swap(Op0, Op1);
4211 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4212 cast<BinaryOperator>(Op0)->swapOperands();
4213 I.swapOperands(); // Simplify below
4214 std::swap(Op0, Op1);
4215 }
4216 }
4217 if (Op1->hasOneUse() &&
4218 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4219 if (B == Op0) { // B&(A^B) -> B&(B^A)
4220 cast<BinaryOperator>(Op1)->swapOperands();
4221 std::swap(A, B);
4222 }
4223 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004224 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004225 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004226 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004227 }
4228 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004229 }
4230
Reid Spencere4d87aa2006-12-23 06:05:41 +00004231 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4232 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4233 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004234 return R;
4235
Chris Lattner955f3312004-09-28 21:48:02 +00004236 Value *LHSVal, *RHSVal;
4237 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004238 ICmpInst::Predicate LHSCC, RHSCC;
4239 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4240 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4241 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4242 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4243 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4244 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4245 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004246 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4247
4248 // Don't try to fold ICMP_SLT + ICMP_ULT.
4249 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4250 ICmpInst::isSignedPredicate(LHSCC) ==
4251 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004252 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004253 ICmpInst::Predicate GT;
4254 if (ICmpInst::isSignedPredicate(LHSCC) ||
4255 (ICmpInst::isEquality(LHSCC) &&
4256 ICmpInst::isSignedPredicate(RHSCC)))
4257 GT = ICmpInst::ICMP_SGT;
4258 else
4259 GT = ICmpInst::ICMP_UGT;
4260
Reid Spencere4d87aa2006-12-23 06:05:41 +00004261 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4262 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004263 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004264 std::swap(LHS, RHS);
4265 std::swap(LHSCst, RHSCst);
4266 std::swap(LHSCC, RHSCC);
4267 }
4268
Reid Spencere4d87aa2006-12-23 06:05:41 +00004269 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004270 // comparing a value against two constants and and'ing the result
4271 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4273 // (from the FoldICmpLogical check above), that the two constants
4274 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004275 assert(LHSCst != RHSCst && "Compares not folded above?");
4276
4277 switch (LHSCC) {
4278 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004279 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004280 switch (RHSCC) {
4281 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004282 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4283 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4284 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004285 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004286 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4287 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4288 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004289 return ReplaceInstUsesWith(I, LHS);
4290 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004291 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004292 switch (RHSCC) {
4293 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004294 case ICmpInst::ICMP_ULT:
4295 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4296 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4297 break; // (X != 13 & X u< 15) -> no change
4298 case ICmpInst::ICMP_SLT:
4299 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4300 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4301 break; // (X != 13 & X s< 15) -> no change
4302 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4303 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4304 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004305 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004306 case ICmpInst::ICMP_NE:
4307 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004308 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004309 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004310 LHSVal->getName()+".off");
4311 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004312 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4313 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004314 }
4315 break; // (X != 13 & X != 15) -> no change
4316 }
4317 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004318 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004319 switch (RHSCC) {
4320 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004321 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4322 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004323 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004324 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4325 break;
4326 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4327 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004328 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004329 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4330 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004331 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004332 break;
4333 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004334 switch (RHSCC) {
4335 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004336 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4337 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004338 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004339 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4340 break;
4341 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4342 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004343 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004344 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4345 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004346 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004347 break;
4348 case ICmpInst::ICMP_UGT:
4349 switch (RHSCC) {
4350 default: assert(0 && "Unknown integer condition code!");
4351 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4352 return ReplaceInstUsesWith(I, LHS);
4353 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4354 return ReplaceInstUsesWith(I, RHS);
4355 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4356 break;
4357 case ICmpInst::ICMP_NE:
4358 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4359 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4360 break; // (X u> 13 & X != 15) -> no change
4361 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4362 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4363 true, I);
4364 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4365 break;
4366 }
4367 break;
4368 case ICmpInst::ICMP_SGT:
4369 switch (RHSCC) {
4370 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004371 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004372 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4373 return ReplaceInstUsesWith(I, RHS);
4374 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4375 break;
4376 case ICmpInst::ICMP_NE:
4377 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4378 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4379 break; // (X s> 13 & X != 15) -> no change
4380 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4381 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4382 true, I);
4383 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4384 break;
4385 }
4386 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004387 }
4388 }
4389 }
4390
Chris Lattner6fc205f2006-05-05 06:39:07 +00004391 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004392 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4393 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4394 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4395 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004396 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004397 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004398 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4399 I.getType(), TD) &&
4400 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4401 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004402 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004403 Op1C->getOperand(0),
4404 I.getName());
4405 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004406 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004407 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004408 }
Chris Lattnere511b742006-11-14 07:46:50 +00004409
4410 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004411 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4412 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4413 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004414 SI0->getOperand(1) == SI1->getOperand(1) &&
4415 (SI0->hasOneUse() || SI1->hasOneUse())) {
4416 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004417 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004418 SI1->getOperand(0),
4419 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004420 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004421 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004422 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004423 }
4424
Chris Lattner99c65742007-10-24 05:38:08 +00004425 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4426 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4427 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4428 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4429 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4430 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4431 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4432 // If either of the constants are nans, then the whole thing returns
4433 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004434 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004435 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4436 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4437 RHS->getOperand(0));
4438 }
4439 }
4440 }
4441
Chris Lattner7e708292002-06-25 16:13:24 +00004442 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004443}
4444
Chris Lattnerafe91a52006-06-15 19:07:26 +00004445/// CollectBSwapParts - Look to see if the specified value defines a single byte
4446/// in the result. If it does, and if the specified byte hasn't been filled in
4447/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004448static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004449 Instruction *I = dyn_cast<Instruction>(V);
4450 if (I == 0) return true;
4451
4452 // If this is an or instruction, it is an inner node of the bswap.
4453 if (I->getOpcode() == Instruction::Or)
4454 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4455 CollectBSwapParts(I->getOperand(1), ByteValues);
4456
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004457 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004458 // If this is a shift by a constant int, and it is "24", then its operand
4459 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004460 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004461 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004462 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004463 8*(ByteValues.size()-1))
4464 return true;
4465
4466 unsigned DestNo;
4467 if (I->getOpcode() == Instruction::Shl) {
4468 // X << 24 defines the top byte with the lowest of the input bytes.
4469 DestNo = ByteValues.size()-1;
4470 } else {
4471 // X >>u 24 defines the low byte with the highest of the input bytes.
4472 DestNo = 0;
4473 }
4474
4475 // If the destination byte value is already defined, the values are or'd
4476 // together, which isn't a bswap (unless it's an or of the same bits).
4477 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4478 return true;
4479 ByteValues[DestNo] = I->getOperand(0);
4480 return false;
4481 }
4482
4483 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4484 // don't have this.
4485 Value *Shift = 0, *ShiftLHS = 0;
4486 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4487 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4488 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4489 return true;
4490 Instruction *SI = cast<Instruction>(Shift);
4491
4492 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004493 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4494 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004495 return true;
4496
4497 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4498 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004499 if (AndAmt->getValue().getActiveBits() > 64)
4500 return true;
4501 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004502 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004503 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004504 break;
4505 // Unknown mask for bswap.
4506 if (DestByte == ByteValues.size()) return true;
4507
Reid Spencerb83eb642006-10-20 07:07:24 +00004508 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004509 unsigned SrcByte;
4510 if (SI->getOpcode() == Instruction::Shl)
4511 SrcByte = DestByte - ShiftBytes;
4512 else
4513 SrcByte = DestByte + ShiftBytes;
4514
4515 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4516 if (SrcByte != ByteValues.size()-DestByte-1)
4517 return true;
4518
4519 // If the destination byte value is already defined, the values are or'd
4520 // together, which isn't a bswap (unless it's an or of the same bits).
4521 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4522 return true;
4523 ByteValues[DestByte] = SI->getOperand(0);
4524 return false;
4525}
4526
4527/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4528/// If so, insert the new bswap intrinsic and return it.
4529Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004530 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4531 if (!ITy || ITy->getBitWidth() % 16)
4532 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004533
4534 /// ByteValues - For each byte of the result, we keep track of which value
4535 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004536 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004537 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004538
4539 // Try to find all the pieces corresponding to the bswap.
4540 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4541 CollectBSwapParts(I.getOperand(1), ByteValues))
4542 return 0;
4543
4544 // Check to see if all of the bytes come from the same value.
4545 Value *V = ByteValues[0];
4546 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4547
4548 // Check to make sure that all of the bytes come from the same value.
4549 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4550 if (ByteValues[i] != V)
4551 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004552 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004553 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004554 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004555 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004556}
4557
4558
Chris Lattner7e708292002-06-25 16:13:24 +00004559Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004560 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004562
Chris Lattner42593e62007-03-24 23:56:43 +00004563 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004564 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004565
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004566 // or X, X = X
4567 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004568 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004569
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004570 // See if we can simplify any instructions used by the instruction whose sole
4571 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004572 if (!isa<VectorType>(I.getType())) {
4573 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4574 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4575 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4576 KnownZero, KnownOne))
4577 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004578 } else if (isa<ConstantAggregateZero>(Op1)) {
4579 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4580 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4581 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4582 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004583 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004584
4585
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004586
Chris Lattner3f5b8772002-05-06 16:14:14 +00004587 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004588 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004589 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004590 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4591 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004592 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004593 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004594 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004595 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004596 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004597 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004598
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004599 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4600 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004601 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004602 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004603 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004604 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004605 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004606 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004607
4608 // Try to fold constant and into select arguments.
4609 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004610 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004611 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004612 if (isa<PHINode>(Op0))
4613 if (Instruction *NV = FoldOpIntoPhi(I))
4614 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004615 }
4616
Chris Lattner4f637d42006-01-06 17:59:59 +00004617 Value *A = 0, *B = 0;
4618 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004619
4620 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4621 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4622 return ReplaceInstUsesWith(I, Op1);
4623 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4624 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4625 return ReplaceInstUsesWith(I, Op0);
4626
Chris Lattner6423d4c2006-07-10 20:25:24 +00004627 // (A | B) | C and A | (B | C) -> bswap if possible.
4628 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004629 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004630 match(Op1, m_Or(m_Value(), m_Value())) ||
4631 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4632 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004633 if (Instruction *BSwap = MatchBSwap(I))
4634 return BSwap;
4635 }
4636
Chris Lattner6e4c6492005-05-09 04:58:36 +00004637 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4638 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004639 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004640 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004641 InsertNewInstBefore(NOr, I);
4642 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004643 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004644 }
4645
4646 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4647 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004648 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004649 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004650 InsertNewInstBefore(NOr, I);
4651 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004652 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004653 }
4654
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004655 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004656 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004657 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4658 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004659 Value *V1 = 0, *V2 = 0, *V3 = 0;
4660 C1 = dyn_cast<ConstantInt>(C);
4661 C2 = dyn_cast<ConstantInt>(D);
4662 if (C1 && C2) { // (A & C1)|(B & C2)
4663 // If we have: ((V + N) & C1) | (V & C2)
4664 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4665 // replace with V+N.
4666 if (C1->getValue() == ~C2->getValue()) {
4667 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4668 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4669 // Add commutes, try both ways.
4670 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4671 return ReplaceInstUsesWith(I, A);
4672 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4673 return ReplaceInstUsesWith(I, A);
4674 }
4675 // Or commutes, try both ways.
4676 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4677 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4678 // Add commutes, try both ways.
4679 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4680 return ReplaceInstUsesWith(I, B);
4681 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4682 return ReplaceInstUsesWith(I, B);
4683 }
4684 }
Chris Lattner044e5332007-04-08 08:01:49 +00004685 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004686 }
4687
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004688 // Check to see if we have any common things being and'ed. If so, find the
4689 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004690 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4691 if (A == B) // (A & C)|(A & D) == A & (C|D)
4692 V1 = A, V2 = C, V3 = D;
4693 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4694 V1 = A, V2 = B, V3 = C;
4695 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4696 V1 = C, V2 = A, V3 = D;
4697 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4698 V1 = C, V2 = A, V3 = B;
4699
4700 if (V1) {
4701 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004702 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4703 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004704 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004705 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004706 }
Chris Lattnere511b742006-11-14 07:46:50 +00004707
4708 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004709 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4710 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4711 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004712 SI0->getOperand(1) == SI1->getOperand(1) &&
4713 (SI0->hasOneUse() || SI1->hasOneUse())) {
4714 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004715 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004716 SI1->getOperand(0),
4717 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004718 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004719 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004720 }
4721 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004722
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004723 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4724 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004725 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004726 } else {
4727 A = 0;
4728 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004729 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004730 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4731 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004732 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004733
Misha Brukmancb6267b2004-07-30 12:50:08 +00004734 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004735 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004736 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004737 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004738 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004739 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004740 }
Chris Lattnera2881962003-02-18 19:28:33 +00004741
Reid Spencere4d87aa2006-12-23 06:05:41 +00004742 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4743 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4744 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004745 return R;
4746
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004747 Value *LHSVal, *RHSVal;
4748 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004749 ICmpInst::Predicate LHSCC, RHSCC;
4750 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4751 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4752 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4753 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4754 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4755 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4756 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004757 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4758 // We can't fold (ugt x, C) | (sgt x, C2).
4759 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004760 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004761 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004762 bool NeedsSwap;
4763 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004764 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004765 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004766 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004767
4768 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004769 std::swap(LHS, RHS);
4770 std::swap(LHSCst, RHSCst);
4771 std::swap(LHSCC, RHSCC);
4772 }
4773
Reid Spencere4d87aa2006-12-23 06:05:41 +00004774 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004775 // comparing a value against two constants and or'ing the result
4776 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004777 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4778 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004779 // equal.
4780 assert(LHSCst != RHSCst && "Compares not folded above?");
4781
4782 switch (LHSCC) {
4783 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004784 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004785 switch (RHSCC) {
4786 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004787 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004788 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4789 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004790 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004791 LHSVal->getName()+".off");
4792 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004793 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004794 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004795 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004796 break; // (X == 13 | X == 15) -> no change
4797 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4798 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004799 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004800 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4801 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4802 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004803 return ReplaceInstUsesWith(I, RHS);
4804 }
4805 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004806 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004807 switch (RHSCC) {
4808 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004809 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4810 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4811 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004812 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004813 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4814 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4815 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004816 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004817 }
4818 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004819 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004820 switch (RHSCC) {
4821 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004822 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004823 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004824 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004825 // If RHSCst is [us]MAXINT, it is always false. Not handling
4826 // this can cause overflow.
4827 if (RHSCst->isMaxValue(false))
4828 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004829 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4830 false, I);
4831 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4832 break;
4833 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4834 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004835 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004836 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4837 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004838 }
4839 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004840 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004841 switch (RHSCC) {
4842 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004843 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4844 break;
4845 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004846 // If RHSCst is [us]MAXINT, it is always false. Not handling
4847 // this can cause overflow.
4848 if (RHSCst->isMaxValue(true))
4849 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004850 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4851 false, I);
4852 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4853 break;
4854 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4855 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4856 return ReplaceInstUsesWith(I, RHS);
4857 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4858 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004859 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004860 break;
4861 case ICmpInst::ICMP_UGT:
4862 switch (RHSCC) {
4863 default: assert(0 && "Unknown integer condition code!");
4864 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4865 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4866 return ReplaceInstUsesWith(I, LHS);
4867 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4868 break;
4869 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4870 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004871 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004872 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4873 break;
4874 }
4875 break;
4876 case ICmpInst::ICMP_SGT:
4877 switch (RHSCC) {
4878 default: assert(0 && "Unknown integer condition code!");
4879 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4880 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4881 return ReplaceInstUsesWith(I, LHS);
4882 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4883 break;
4884 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4885 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004887 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4888 break;
4889 }
4890 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004891 }
4892 }
4893 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004894
4895 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004896 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004897 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004898 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004899 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4900 !isa<ICmpInst>(Op1C->getOperand(0))) {
4901 const Type *SrcTy = Op0C->getOperand(0)->getType();
4902 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4903 // Only do this if the casts both really cause code to be
4904 // generated.
4905 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4906 I.getType(), TD) &&
4907 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4908 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004909 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004910 Op1C->getOperand(0),
4911 I.getName());
4912 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004913 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004914 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004915 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004916 }
Chris Lattner99c65742007-10-24 05:38:08 +00004917 }
4918
4919
4920 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4921 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4922 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4923 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004924 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4925 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004926 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4927 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4928 // If either of the constants are nans, then the whole thing returns
4929 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004930 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004931 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4932
4933 // Otherwise, no need to compare the two constants, compare the
4934 // rest.
4935 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4936 RHS->getOperand(0));
4937 }
4938 }
4939 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004940
Chris Lattner7e708292002-06-25 16:13:24 +00004941 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004942}
4943
Dan Gohman844731a2008-05-13 00:00:25 +00004944namespace {
4945
Chris Lattnerc317d392004-02-16 01:20:27 +00004946// XorSelf - Implements: X ^ X --> 0
4947struct XorSelf {
4948 Value *RHS;
4949 XorSelf(Value *rhs) : RHS(rhs) {}
4950 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4951 Instruction *apply(BinaryOperator &Xor) const {
4952 return &Xor;
4953 }
4954};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004955
Dan Gohman844731a2008-05-13 00:00:25 +00004956}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004957
Chris Lattner7e708292002-06-25 16:13:24 +00004958Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004959 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004961
Evan Chengd34af782008-03-25 20:07:13 +00004962 if (isa<UndefValue>(Op1)) {
4963 if (isa<UndefValue>(Op0))
4964 // Handle undef ^ undef -> 0 special case. This is a common
4965 // idiom (misuse).
4966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004967 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004968 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004969
Chris Lattnerc317d392004-02-16 01:20:27 +00004970 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4971 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004972 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004973 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004974 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004975
4976 // See if we can simplify any instructions used by the instruction whose sole
4977 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004978 if (!isa<VectorType>(I.getType())) {
4979 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4980 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4981 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4982 KnownZero, KnownOne))
4983 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004984 } else if (isa<ConstantAggregateZero>(Op1)) {
4985 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004986 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004987
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004988 // Is this a ~ operation?
4989 if (Value *NotOp = dyn_castNotVal(&I)) {
4990 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4991 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4992 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4993 if (Op0I->getOpcode() == Instruction::And ||
4994 Op0I->getOpcode() == Instruction::Or) {
4995 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4996 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4997 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004998 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004999 Op0I->getOperand(1)->getName()+".not");
5000 InsertNewInstBefore(NotY, I);
5001 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005002 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005003 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005004 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005005 }
5006 }
5007 }
5008 }
5009
5010
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005012 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5013 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5014 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005015 return new ICmpInst(ICI->getInversePredicate(),
5016 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005017
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005018 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5019 return new FCmpInst(FCI->getInversePredicate(),
5020 FCI->getOperand(0), FCI->getOperand(1));
5021 }
5022
Reid Spencere4d87aa2006-12-23 06:05:41 +00005023 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005024 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005025 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5026 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005027 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5028 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005029 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005030 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005031 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005032
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005033 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005034 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005035 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005036 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005037 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005038 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005039 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005040 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005041 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005042 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005043 // (X + C) ^ signbit -> (X + C + signbit)
5044 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005045 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005046
Chris Lattner7c4049c2004-01-12 19:35:11 +00005047 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005048 } else if (Op0I->getOpcode() == Instruction::Or) {
5049 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005050 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005051 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5052 // Anything in both C1 and C2 is known to be zero, remove it from
5053 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005054 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005055 NewRHS = ConstantExpr::getAnd(NewRHS,
5056 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005057 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005058 I.setOperand(0, Op0I->getOperand(0));
5059 I.setOperand(1, NewRHS);
5060 return &I;
5061 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005062 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005063 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005064 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005065
5066 // Try to fold constant and into select arguments.
5067 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005068 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005069 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005070 if (isa<PHINode>(Op0))
5071 if (Instruction *NV = FoldOpIntoPhi(I))
5072 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005073 }
5074
Chris Lattner8d969642003-03-10 23:06:50 +00005075 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005076 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005077 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005078
Chris Lattner8d969642003-03-10 23:06:50 +00005079 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005080 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005081 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005082
Chris Lattner318bf792007-03-18 22:51:34 +00005083
5084 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5085 if (Op1I) {
5086 Value *A, *B;
5087 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5088 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005089 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005090 I.swapOperands();
5091 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005092 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005093 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005094 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005095 }
Chris Lattner318bf792007-03-18 22:51:34 +00005096 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5097 if (Op0 == A) // A^(A^B) == B
5098 return ReplaceInstUsesWith(I, B);
5099 else if (Op0 == B) // A^(B^A) == B
5100 return ReplaceInstUsesWith(I, A);
5101 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005102 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005103 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005104 std::swap(A, B);
5105 }
Chris Lattner318bf792007-03-18 22:51:34 +00005106 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005107 I.swapOperands(); // Simplified below.
5108 std::swap(Op0, Op1);
5109 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005110 }
Chris Lattner318bf792007-03-18 22:51:34 +00005111 }
5112
5113 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5114 if (Op0I) {
5115 Value *A, *B;
5116 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5117 if (A == Op1) // (B|A)^B == (A|B)^B
5118 std::swap(A, B);
5119 if (B == Op1) { // (A|B)^B == A & ~B
5120 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005121 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5122 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005123 }
Chris Lattner318bf792007-03-18 22:51:34 +00005124 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5125 if (Op1 == A) // (A^B)^A == B
5126 return ReplaceInstUsesWith(I, B);
5127 else if (Op1 == B) // (B^A)^A == B
5128 return ReplaceInstUsesWith(I, A);
5129 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5130 if (A == Op1) // (A&B)^A -> (B&A)^A
5131 std::swap(A, B);
5132 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005133 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005134 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005135 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5136 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005137 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005138 }
Chris Lattner318bf792007-03-18 22:51:34 +00005139 }
5140
5141 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5142 if (Op0I && Op1I && Op0I->isShift() &&
5143 Op0I->getOpcode() == Op1I->getOpcode() &&
5144 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5145 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5146 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005147 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005148 Op1I->getOperand(0),
5149 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005150 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005151 Op1I->getOperand(1));
5152 }
5153
5154 if (Op0I && Op1I) {
5155 Value *A, *B, *C, *D;
5156 // (A & B)^(A | B) -> A ^ B
5157 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5158 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5159 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005160 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005161 }
5162 // (A | B)^(A & B) -> A ^ B
5163 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5164 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5165 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005166 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005167 }
5168
5169 // (A & B)^(C & D)
5170 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5171 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5172 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5173 // (X & Y)^(X & Y) -> (Y^Z) & X
5174 Value *X = 0, *Y = 0, *Z = 0;
5175 if (A == C)
5176 X = A, Y = B, Z = D;
5177 else if (A == D)
5178 X = A, Y = B, Z = C;
5179 else if (B == C)
5180 X = B, Y = A, Z = D;
5181 else if (B == D)
5182 X = B, Y = A, Z = C;
5183
5184 if (X) {
5185 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005186 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5187 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005188 }
5189 }
5190 }
5191
Reid Spencere4d87aa2006-12-23 06:05:41 +00005192 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5193 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5194 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005195 return R;
5196
Chris Lattner6fc205f2006-05-05 06:39:07 +00005197 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005198 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005199 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005200 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5201 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005202 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005203 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005204 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5205 I.getType(), TD) &&
5206 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5207 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005208 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005209 Op1C->getOperand(0),
5210 I.getName());
5211 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005212 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005213 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005214 }
Chris Lattner99c65742007-10-24 05:38:08 +00005215 }
Chris Lattner7e708292002-06-25 16:13:24 +00005216 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005217}
5218
Chris Lattnera96879a2004-09-29 17:40:11 +00005219/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5220/// overflowed for this type.
5221static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005222 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005223 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005224
Reid Spencere4e40032007-03-21 23:19:50 +00005225 if (IsSigned)
5226 if (In2->getValue().isNegative())
5227 return Result->getValue().sgt(In1->getValue());
5228 else
5229 return Result->getValue().slt(In1->getValue());
5230 else
5231 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005232}
5233
Chris Lattner574da9b2005-01-13 20:14:25 +00005234/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5235/// code necessary to compute the offset from the base pointer (without adding
5236/// in the base pointer). Return the result as a signed integer of intptr size.
5237static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5238 TargetData &TD = IC.getTargetData();
5239 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005240 const Type *IntPtrTy = TD.getIntPtrType();
5241 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005242
5243 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005244 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005245 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005246
Chris Lattner574da9b2005-01-13 20:14:25 +00005247 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5248 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005249 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005250 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5251 if (OpC->isZero()) continue;
5252
5253 // Handle a struct index, which adds its field offset to the pointer.
5254 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5255 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5256
5257 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5258 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005259 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005260 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005261 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005262 ConstantInt::get(IntPtrTy, Size),
5263 GEP->getName()+".offs"), I);
5264 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005265 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005266
5267 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5268 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5269 Scale = ConstantExpr::getMul(OC, Scale);
5270 if (Constant *RC = dyn_cast<Constant>(Result))
5271 Result = ConstantExpr::getAdd(RC, Scale);
5272 else {
5273 // Emit an add instruction.
5274 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005275 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005276 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005277 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005278 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005279 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005280 // Convert to correct type.
5281 if (Op->getType() != IntPtrTy) {
5282 if (Constant *OpC = dyn_cast<Constant>(Op))
5283 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5284 else
5285 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5286 Op->getName()+".c"), I);
5287 }
5288 if (Size != 1) {
5289 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5290 if (Constant *OpC = dyn_cast<Constant>(Op))
5291 Op = ConstantExpr::getMul(OpC, Scale);
5292 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005293 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005294 GEP->getName()+".idx"), I);
5295 }
5296
5297 // Emit an add instruction.
5298 if (isa<Constant>(Op) && isa<Constant>(Result))
5299 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5300 cast<Constant>(Result));
5301 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005302 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005303 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005304 }
5305 return Result;
5306}
5307
Chris Lattner10c0d912008-04-22 02:53:33 +00005308
5309/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5310/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5311/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5312/// complex, and scales are involved. The above expression would also be legal
5313/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5314/// later form is less amenable to optimization though, and we are allowed to
5315/// generate the first by knowing that pointer arithmetic doesn't overflow.
5316///
5317/// If we can't emit an optimized form for this expression, this returns null.
5318///
5319static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5320 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005321 TargetData &TD = IC.getTargetData();
5322 gep_type_iterator GTI = gep_type_begin(GEP);
5323
5324 // Check to see if this gep only has a single variable index. If so, and if
5325 // any constant indices are a multiple of its scale, then we can compute this
5326 // in terms of the scale of the variable index. For example, if the GEP
5327 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5328 // because the expression will cross zero at the same point.
5329 unsigned i, e = GEP->getNumOperands();
5330 int64_t Offset = 0;
5331 for (i = 1; i != e; ++i, ++GTI) {
5332 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5333 // Compute the aggregate offset of constant indices.
5334 if (CI->isZero()) continue;
5335
5336 // Handle a struct index, which adds its field offset to the pointer.
5337 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5338 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5339 } else {
5340 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5341 Offset += Size*CI->getSExtValue();
5342 }
5343 } else {
5344 // Found our variable index.
5345 break;
5346 }
5347 }
5348
5349 // If there are no variable indices, we must have a constant offset, just
5350 // evaluate it the general way.
5351 if (i == e) return 0;
5352
5353 Value *VariableIdx = GEP->getOperand(i);
5354 // Determine the scale factor of the variable element. For example, this is
5355 // 4 if the variable index is into an array of i32.
5356 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5357
5358 // Verify that there are no other variable indices. If so, emit the hard way.
5359 for (++i, ++GTI; i != e; ++i, ++GTI) {
5360 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5361 if (!CI) return 0;
5362
5363 // Compute the aggregate offset of constant indices.
5364 if (CI->isZero()) continue;
5365
5366 // Handle a struct index, which adds its field offset to the pointer.
5367 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5368 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5369 } else {
5370 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5371 Offset += Size*CI->getSExtValue();
5372 }
5373 }
5374
5375 // Okay, we know we have a single variable index, which must be a
5376 // pointer/array/vector index. If there is no offset, life is simple, return
5377 // the index.
5378 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5379 if (Offset == 0) {
5380 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5381 // we don't need to bother extending: the extension won't affect where the
5382 // computation crosses zero.
5383 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5384 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5385 VariableIdx->getNameStart(), &I);
5386 return VariableIdx;
5387 }
5388
5389 // Otherwise, there is an index. The computation we will do will be modulo
5390 // the pointer size, so get it.
5391 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5392
5393 Offset &= PtrSizeMask;
5394 VariableScale &= PtrSizeMask;
5395
5396 // To do this transformation, any constant index must be a multiple of the
5397 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5398 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5399 // multiple of the variable scale.
5400 int64_t NewOffs = Offset / (int64_t)VariableScale;
5401 if (Offset != NewOffs*(int64_t)VariableScale)
5402 return 0;
5403
5404 // Okay, we can do this evaluation. Start by converting the index to intptr.
5405 const Type *IntPtrTy = TD.getIntPtrType();
5406 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005407 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005408 true /*SExt*/,
5409 VariableIdx->getNameStart(), &I);
5410 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005411 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005412}
5413
5414
Reid Spencere4d87aa2006-12-23 06:05:41 +00005415/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005416/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005417Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5418 ICmpInst::Predicate Cond,
5419 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005420 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005421
Chris Lattner10c0d912008-04-22 02:53:33 +00005422 // Look through bitcasts.
5423 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5424 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005425
Chris Lattner574da9b2005-01-13 20:14:25 +00005426 Value *PtrBase = GEPLHS->getOperand(0);
5427 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005428 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005429 // This transformation (ignoring the base and scales) is valid because we
5430 // know pointers can't overflow. See if we can output an optimized form.
5431 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5432
5433 // If not, synthesize the offset the hard way.
5434 if (Offset == 0)
5435 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005436 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5437 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005438 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005439 // If the base pointers are different, but the indices are the same, just
5440 // compare the base pointer.
5441 if (PtrBase != GEPRHS->getOperand(0)) {
5442 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005443 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005444 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005445 if (IndicesTheSame)
5446 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5447 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5448 IndicesTheSame = false;
5449 break;
5450 }
5451
5452 // If all indices are the same, just compare the base pointers.
5453 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005454 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5455 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005456
5457 // Otherwise, the base pointers are different and the indices are
5458 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005459 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005460 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005461
Chris Lattnere9d782b2005-01-13 22:25:21 +00005462 // If one of the GEPs has all zero indices, recurse.
5463 bool AllZeros = true;
5464 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5465 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5466 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5467 AllZeros = false;
5468 break;
5469 }
5470 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005471 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5472 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005473
5474 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005475 AllZeros = true;
5476 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5477 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5478 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5479 AllZeros = false;
5480 break;
5481 }
5482 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005483 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005484
Chris Lattner4401c9c2005-01-14 00:20:05 +00005485 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5486 // If the GEPs only differ by one index, compare it.
5487 unsigned NumDifferences = 0; // Keep track of # differences.
5488 unsigned DiffOperand = 0; // The operand that differs.
5489 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5490 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005491 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5492 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005493 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005494 NumDifferences = 2;
5495 break;
5496 } else {
5497 if (NumDifferences++) break;
5498 DiffOperand = i;
5499 }
5500 }
5501
5502 if (NumDifferences == 0) // SAME GEP?
5503 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005504 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005505 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005506
Chris Lattner4401c9c2005-01-14 00:20:05 +00005507 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005508 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5509 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005510 // Make sure we do a signed comparison here.
5511 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005512 }
5513 }
5514
Reid Spencere4d87aa2006-12-23 06:05:41 +00005515 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005516 // the result to fold to a constant!
5517 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5518 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5519 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5520 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5521 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005522 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005523 }
5524 }
5525 return 0;
5526}
5527
Chris Lattnera5406232008-05-19 20:18:56 +00005528/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5529///
5530Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5531 Instruction *LHSI,
5532 Constant *RHSC) {
5533 if (!isa<ConstantFP>(RHSC)) return 0;
5534 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5535
5536 // Get the width of the mantissa. We don't want to hack on conversions that
5537 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005538 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005539 if (MantissaWidth == -1) return 0; // Unknown.
5540
5541 // Check to see that the input is converted from an integer type that is small
5542 // enough that preserves all bits. TODO: check here for "known" sign bits.
5543 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5544 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5545
5546 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5547 if (isa<UIToFPInst>(LHSI))
5548 ++InputSize;
5549
5550 // If the conversion would lose info, don't hack on this.
5551 if ((int)InputSize > MantissaWidth)
5552 return 0;
5553
5554 // Otherwise, we can potentially simplify the comparison. We know that it
5555 // will always come through as an integer value and we know the constant is
5556 // not a NAN (it would have been previously simplified).
5557 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5558
5559 ICmpInst::Predicate Pred;
5560 switch (I.getPredicate()) {
5561 default: assert(0 && "Unexpected predicate!");
5562 case FCmpInst::FCMP_UEQ:
5563 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5564 case FCmpInst::FCMP_UGT:
5565 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5566 case FCmpInst::FCMP_UGE:
5567 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5568 case FCmpInst::FCMP_ULT:
5569 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5570 case FCmpInst::FCMP_ULE:
5571 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5572 case FCmpInst::FCMP_UNE:
5573 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5574 case FCmpInst::FCMP_ORD:
5575 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5576 case FCmpInst::FCMP_UNO:
5577 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5578 }
5579
5580 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5581
5582 // Now we know that the APFloat is a normal number, zero or inf.
5583
Chris Lattner85162782008-05-20 03:50:52 +00005584 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005585 // comparing an i8 to 300.0.
5586 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5587
5588 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5589 // and large values.
5590 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5591 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5592 APFloat::rmNearestTiesToEven);
5593 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5594 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5595 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5596 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5597 }
5598
5599 // See if the RHS value is < SignedMin.
5600 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5601 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5602 APFloat::rmNearestTiesToEven);
5603 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5604 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5605 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5606 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5607 }
5608
5609 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5610 // it may still be fractional. See if it is fractional by casting the FP
5611 // value to the integer value and back, checking for equality. Don't do this
5612 // for zero, because -0.0 is not fractional.
5613 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5614 if (!RHS.isZero() &&
5615 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5616 // If we had a comparison against a fractional value, we have to adjust
5617 // the compare predicate and sometimes the value. RHSC is rounded towards
5618 // zero at this point.
5619 switch (Pred) {
5620 default: assert(0 && "Unexpected integer comparison!");
5621 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5622 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5623 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5624 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5625 case ICmpInst::ICMP_SLE:
5626 // (float)int <= 4.4 --> int <= 4
5627 // (float)int <= -4.4 --> int < -4
5628 if (RHS.isNegative())
5629 Pred = ICmpInst::ICMP_SLT;
5630 break;
5631 case ICmpInst::ICMP_SLT:
5632 // (float)int < -4.4 --> int < -4
5633 // (float)int < 4.4 --> int <= 4
5634 if (!RHS.isNegative())
5635 Pred = ICmpInst::ICMP_SLE;
5636 break;
5637 case ICmpInst::ICMP_SGT:
5638 // (float)int > 4.4 --> int > 4
5639 // (float)int > -4.4 --> int >= -4
5640 if (RHS.isNegative())
5641 Pred = ICmpInst::ICMP_SGE;
5642 break;
5643 case ICmpInst::ICMP_SGE:
5644 // (float)int >= -4.4 --> int >= -4
5645 // (float)int >= 4.4 --> int > 4
5646 if (!RHS.isNegative())
5647 Pred = ICmpInst::ICMP_SGT;
5648 break;
5649 }
5650 }
5651
5652 // Lower this FP comparison into an appropriate integer version of the
5653 // comparison.
5654 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5655}
5656
Reid Spencere4d87aa2006-12-23 06:05:41 +00005657Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5658 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005660
Chris Lattner58e97462007-01-14 19:42:17 +00005661 // Fold trivial predicates.
5662 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5663 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5664 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5665 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5666
5667 // Simplify 'fcmp pred X, X'
5668 if (Op0 == Op1) {
5669 switch (I.getPredicate()) {
5670 default: assert(0 && "Unknown predicate!");
5671 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5672 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5673 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5674 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5675 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5676 case FCmpInst::FCMP_OLT: // True if ordered and less than
5677 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5678 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5679
5680 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5681 case FCmpInst::FCMP_ULT: // True if unordered or less than
5682 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5683 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5684 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5685 I.setPredicate(FCmpInst::FCMP_UNO);
5686 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5687 return &I;
5688
5689 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5690 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5691 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5692 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5693 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5694 I.setPredicate(FCmpInst::FCMP_ORD);
5695 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5696 return &I;
5697 }
5698 }
5699
Reid Spencere4d87aa2006-12-23 06:05:41 +00005700 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005701 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005702
Reid Spencere4d87aa2006-12-23 06:05:41 +00005703 // Handle fcmp with constant RHS
5704 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005705 // If the constant is a nan, see if we can fold the comparison based on it.
5706 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5707 if (CFP->getValueAPF().isNaN()) {
5708 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5709 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005710 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5711 "Comparison must be either ordered or unordered!");
5712 // True if unordered.
5713 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005714 }
5715 }
5716
Reid Spencere4d87aa2006-12-23 06:05:41 +00005717 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5718 switch (LHSI->getOpcode()) {
5719 case Instruction::PHI:
5720 if (Instruction *NV = FoldOpIntoPhi(I))
5721 return NV;
5722 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005723 case Instruction::SIToFP:
5724 case Instruction::UIToFP:
5725 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5726 return NV;
5727 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005728 case Instruction::Select:
5729 // If either operand of the select is a constant, we can fold the
5730 // comparison into the select arms, which will cause one to be
5731 // constant folded and the select turned into a bitwise or.
5732 Value *Op1 = 0, *Op2 = 0;
5733 if (LHSI->hasOneUse()) {
5734 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5735 // Fold the known value into the constant operand.
5736 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5737 // Insert a new FCmp of the other select operand.
5738 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5739 LHSI->getOperand(2), RHSC,
5740 I.getName()), I);
5741 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5742 // Fold the known value into the constant operand.
5743 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5744 // Insert a new FCmp of the other select operand.
5745 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5746 LHSI->getOperand(1), RHSC,
5747 I.getName()), I);
5748 }
5749 }
5750
5751 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005752 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005753 break;
5754 }
5755 }
5756
5757 return Changed ? &I : 0;
5758}
5759
5760Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5761 bool Changed = SimplifyCompare(I);
5762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5763 const Type *Ty = Op0->getType();
5764
5765 // icmp X, X
5766 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005767 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005768 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005769
5770 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005771 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005772
Reid Spencere4d87aa2006-12-23 06:05:41 +00005773 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005774 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005775 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5776 isa<ConstantPointerNull>(Op0)) &&
5777 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005778 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005779 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005780 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005781
Reid Spencere4d87aa2006-12-23 06:05:41 +00005782 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005783 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005784 switch (I.getPredicate()) {
5785 default: assert(0 && "Invalid icmp instruction!");
5786 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005787 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005788 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005789 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005790 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005791 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005792 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005793
Reid Spencere4d87aa2006-12-23 06:05:41 +00005794 case ICmpInst::ICMP_UGT:
5795 case ICmpInst::ICMP_SGT:
5796 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005797 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005798 case ICmpInst::ICMP_ULT:
5799 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005800 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005801 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005802 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005803 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005804 case ICmpInst::ICMP_UGE:
5805 case ICmpInst::ICMP_SGE:
5806 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005807 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005808 case ICmpInst::ICMP_ULE:
5809 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005810 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005811 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005812 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005813 }
5814 }
Chris Lattner8b170942002-08-09 23:47:40 +00005815 }
5816
Chris Lattner2be51ae2004-06-09 04:24:29 +00005817 // See if we are doing a comparison between a constant and an instruction that
5818 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005819 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005820 Value *A, *B;
5821
Chris Lattnerb6566012008-01-05 01:18:20 +00005822 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5823 if (I.isEquality() && CI->isNullValue() &&
5824 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5825 // (icmp cond A B) if cond is equality
5826 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005827 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005828
Reid Spencere4d87aa2006-12-23 06:05:41 +00005829 switch (I.getPredicate()) {
5830 default: break;
5831 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5832 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005833 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005834 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5835 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5836 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5837 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005838 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5839 if (CI->isMinValue(true))
5840 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5841 ConstantInt::getAllOnesValue(Op0->getType()));
5842
Reid Spencere4d87aa2006-12-23 06:05:41 +00005843 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005844
Reid Spencere4d87aa2006-12-23 06:05:41 +00005845 case ICmpInst::ICMP_SLT:
5846 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005848 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5849 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5850 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5851 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5852 break;
5853
5854 case ICmpInst::ICMP_UGT:
5855 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005856 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005857 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5858 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5859 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5860 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005861
5862 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5863 if (CI->isMaxValue(true))
5864 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5865 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005866 break;
5867
5868 case ICmpInst::ICMP_SGT:
5869 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005870 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005871 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5872 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5873 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5874 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5875 break;
5876
5877 case ICmpInst::ICMP_ULE:
5878 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005879 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005880 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5881 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5882 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5883 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5884 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005885
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886 case ICmpInst::ICMP_SLE:
5887 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005889 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5890 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5891 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5892 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5893 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005894
Reid Spencere4d87aa2006-12-23 06:05:41 +00005895 case ICmpInst::ICMP_UGE:
5896 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005897 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005898 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5899 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5900 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5901 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5902 break;
5903
5904 case ICmpInst::ICMP_SGE:
5905 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005906 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005907 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5908 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5909 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5910 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5911 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005912 }
5913
Reid Spencere4d87aa2006-12-23 06:05:41 +00005914 // If we still have a icmp le or icmp ge instruction, turn it into the
5915 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005916 // already been handled above, this requires little checking.
5917 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005918 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005919 default: break;
5920 case ICmpInst::ICMP_ULE:
5921 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5922 case ICmpInst::ICMP_SLE:
5923 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5924 case ICmpInst::ICMP_UGE:
5925 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5926 case ICmpInst::ICMP_SGE:
5927 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005928 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005929
5930 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005931 // in the input. If this comparison is a normal comparison, it demands all
5932 // bits, if it is a sign bit comparison, it only demands the sign bit.
5933
5934 bool UnusedBit;
5935 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5936
Reid Spencer0460fb32007-03-22 20:36:03 +00005937 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5938 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005939 if (SimplifyDemandedBits(Op0,
5940 isSignBit ? APInt::getSignBit(BitWidth)
5941 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005942 KnownZero, KnownOne, 0))
5943 return &I;
5944
5945 // Given the known and unknown bits, compute a range that the LHS could be
5946 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005947 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005948 // Compute the Min, Max and RHS values based on the known bits. For the
5949 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005950 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5951 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005952 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005953 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5954 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005956 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5957 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958 }
5959 switch (I.getPredicate()) { // LE/GE have been folded already.
5960 default: assert(0 && "Unknown icmp opcode!");
5961 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005962 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005963 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005964 break;
5965 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005966 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005967 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005968 break;
5969 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005970 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005971 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005972 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005973 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 break;
5975 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005976 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005977 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005978 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005979 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005980 break;
5981 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005982 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005983 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005984 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005985 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005986 break;
5987 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005988 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005989 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005990 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005991 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005992 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005993 }
5994 }
5995
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005997 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005998 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005999 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006000 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6001 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006002 }
6003
Chris Lattner01deb9d2007-04-03 17:43:25 +00006004 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006005 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6006 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6007 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006008 case Instruction::GetElementPtr:
6009 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006010 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006011 bool isAllZeros = true;
6012 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6013 if (!isa<Constant>(LHSI->getOperand(i)) ||
6014 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6015 isAllZeros = false;
6016 break;
6017 }
6018 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006019 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006020 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6021 }
6022 break;
6023
Chris Lattner6970b662005-04-23 15:31:55 +00006024 case Instruction::PHI:
6025 if (Instruction *NV = FoldOpIntoPhi(I))
6026 return NV;
6027 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006028 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006029 // If either operand of the select is a constant, we can fold the
6030 // comparison into the select arms, which will cause one to be
6031 // constant folded and the select turned into a bitwise or.
6032 Value *Op1 = 0, *Op2 = 0;
6033 if (LHSI->hasOneUse()) {
6034 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6035 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006036 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6037 // Insert a new ICmp of the other select operand.
6038 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6039 LHSI->getOperand(2), RHSC,
6040 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006041 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6042 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006043 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6044 // Insert a new ICmp of the other select operand.
6045 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6046 LHSI->getOperand(1), RHSC,
6047 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006048 }
6049 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006050
Chris Lattner6970b662005-04-23 15:31:55 +00006051 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006052 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006053 break;
6054 }
Chris Lattner4802d902007-04-06 18:57:34 +00006055 case Instruction::Malloc:
6056 // If we have (malloc != null), and if the malloc has a single use, we
6057 // can assume it is successful and remove the malloc.
6058 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6059 AddToWorkList(LHSI);
6060 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006061 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006062 }
6063 break;
6064 }
Chris Lattner6970b662005-04-23 15:31:55 +00006065 }
6066
Reid Spencere4d87aa2006-12-23 06:05:41 +00006067 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006068 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006069 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006070 return NI;
6071 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006072 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6073 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006074 return NI;
6075
Reid Spencere4d87aa2006-12-23 06:05:41 +00006076 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006077 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6078 // now.
6079 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6080 if (isa<PointerType>(Op0->getType()) &&
6081 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006082 // We keep moving the cast from the left operand over to the right
6083 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006084 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006085
Chris Lattner57d86372007-01-06 01:45:59 +00006086 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6087 // so eliminate it as well.
6088 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6089 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006090
Chris Lattnerde90b762003-11-03 04:25:02 +00006091 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006092 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006093 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006094 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006095 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006096 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006097 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006098 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006099 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006100 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006101 }
Chris Lattner57d86372007-01-06 01:45:59 +00006102 }
6103
6104 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006105 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006106 // This comes up when you have code like
6107 // int X = A < B;
6108 // if (X) ...
6109 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006110 // with a constant or another cast from the same type.
6111 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006112 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006113 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006114 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006115
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006116 // ~x < ~y --> y < x
6117 { Value *A, *B;
6118 if (match(Op0, m_Not(m_Value(A))) &&
6119 match(Op1, m_Not(m_Value(B))))
6120 return new ICmpInst(I.getPredicate(), B, A);
6121 }
6122
Chris Lattner65b72ba2006-09-18 04:22:48 +00006123 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006124 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006125
6126 // -x == -y --> x == y
6127 if (match(Op0, m_Neg(m_Value(A))) &&
6128 match(Op1, m_Neg(m_Value(B))))
6129 return new ICmpInst(I.getPredicate(), A, B);
6130
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006131 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6132 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6133 Value *OtherVal = A == Op1 ? B : A;
6134 return new ICmpInst(I.getPredicate(), OtherVal,
6135 Constant::getNullValue(A->getType()));
6136 }
6137
6138 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6139 // A^c1 == C^c2 --> A == C^(c1^c2)
6140 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6141 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6142 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006143 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006144 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006145 return new ICmpInst(I.getPredicate(), A,
6146 InsertNewInstBefore(Xor, I));
6147 }
6148
6149 // A^B == A^D -> B == D
6150 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6151 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6152 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6153 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6154 }
6155 }
6156
6157 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6158 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006159 // A == (A^B) -> B == 0
6160 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006161 return new ICmpInst(I.getPredicate(), OtherVal,
6162 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006163 }
6164 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006165 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006166 return new ICmpInst(I.getPredicate(), B,
6167 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006168 }
6169 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006170 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006171 return new ICmpInst(I.getPredicate(), B,
6172 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006173 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006174
Chris Lattner9c2328e2006-11-14 06:06:06 +00006175 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6176 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6177 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6178 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6179 Value *X = 0, *Y = 0, *Z = 0;
6180
6181 if (A == C) {
6182 X = B; Y = D; Z = A;
6183 } else if (A == D) {
6184 X = B; Y = C; Z = A;
6185 } else if (B == C) {
6186 X = A; Y = D; Z = B;
6187 } else if (B == D) {
6188 X = A; Y = C; Z = B;
6189 }
6190
6191 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006192 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6193 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006194 I.setOperand(0, Op1);
6195 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6196 return &I;
6197 }
6198 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006199 }
Chris Lattner7e708292002-06-25 16:13:24 +00006200 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006201}
6202
Chris Lattner562ef782007-06-20 23:46:26 +00006203
6204/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6205/// and CmpRHS are both known to be integer constants.
6206Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6207 ConstantInt *DivRHS) {
6208 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6209 const APInt &CmpRHSV = CmpRHS->getValue();
6210
6211 // FIXME: If the operand types don't match the type of the divide
6212 // then don't attempt this transform. The code below doesn't have the
6213 // logic to deal with a signed divide and an unsigned compare (and
6214 // vice versa). This is because (x /s C1) <s C2 produces different
6215 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6216 // (x /u C1) <u C2. Simply casting the operands and result won't
6217 // work. :( The if statement below tests that condition and bails
6218 // if it finds it.
6219 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6220 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6221 return 0;
6222 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006223 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006224
6225 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6226 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6227 // C2 (CI). By solving for X we can turn this into a range check
6228 // instead of computing a divide.
6229 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6230
6231 // Determine if the product overflows by seeing if the product is
6232 // not equal to the divide. Make sure we do the same kind of divide
6233 // as in the LHS instruction that we're folding.
6234 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6235 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6236
6237 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006238 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006239
Chris Lattner1dbfd482007-06-21 18:11:19 +00006240 // Figure out the interval that is being checked. For example, a comparison
6241 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6242 // Compute this interval based on the constants involved and the signedness of
6243 // the compare/divide. This computes a half-open interval, keeping track of
6244 // whether either value in the interval overflows. After analysis each
6245 // overflow variable is set to 0 if it's corresponding bound variable is valid
6246 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6247 int LoOverflow = 0, HiOverflow = 0;
6248 ConstantInt *LoBound = 0, *HiBound = 0;
6249
6250
Chris Lattner562ef782007-06-20 23:46:26 +00006251 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006252 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006253 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006254 HiOverflow = LoOverflow = ProdOV;
6255 if (!HiOverflow)
6256 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006257 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006258 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006259 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006260 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6261 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006262 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006263 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6264 HiOverflow = LoOverflow = ProdOV;
6265 if (!HiOverflow)
6266 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006267 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006268 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006269 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6270 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006271 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006272 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006273 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006274 }
Dan Gohman76491272008-02-13 22:09:18 +00006275 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006276 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006277 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006278 LoBound = AddOne(DivRHS);
6279 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006280 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6281 HiOverflow = 1; // [INTMIN+1, overflow)
6282 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6283 }
Dan Gohman76491272008-02-13 22:09:18 +00006284 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006285 // e.g. X/-5 op 3 --> [-19, -14)
6286 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006287 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006288 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006289 HiBound = AddOne(Prod);
6290 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006291 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006292 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006293 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006294 HiBound = Subtract(Prod, DivRHS);
6295 }
6296
Chris Lattner1dbfd482007-06-21 18:11:19 +00006297 // Dividing by a negative swaps the condition. LT <-> GT
6298 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006299 }
6300
6301 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006302 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006303 default: assert(0 && "Unhandled icmp opcode!");
6304 case ICmpInst::ICMP_EQ:
6305 if (LoOverflow && HiOverflow)
6306 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6307 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006308 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006309 ICmpInst::ICMP_UGE, X, LoBound);
6310 else if (LoOverflow)
6311 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6312 ICmpInst::ICMP_ULT, X, HiBound);
6313 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006314 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006315 case ICmpInst::ICMP_NE:
6316 if (LoOverflow && HiOverflow)
6317 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6318 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006319 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006320 ICmpInst::ICMP_ULT, X, LoBound);
6321 else if (LoOverflow)
6322 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6323 ICmpInst::ICMP_UGE, X, HiBound);
6324 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006325 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006326 case ICmpInst::ICMP_ULT:
6327 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006328 if (LoOverflow == +1) // Low bound is greater than input range.
6329 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6330 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006331 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006332 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006333 case ICmpInst::ICMP_UGT:
6334 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006335 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006336 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006337 else if (HiOverflow == -1) // High bound less than input range.
6338 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6339 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006340 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6341 else
6342 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6343 }
6344}
6345
6346
Chris Lattner01deb9d2007-04-03 17:43:25 +00006347/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6348///
6349Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6350 Instruction *LHSI,
6351 ConstantInt *RHS) {
6352 const APInt &RHSV = RHS->getValue();
6353
6354 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006355 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006356 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6357 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6358 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006359 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6360 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006361 Value *CompareVal = LHSI->getOperand(0);
6362
6363 // If the sign bit of the XorCST is not set, there is no change to
6364 // the operation, just stop using the Xor.
6365 if (!XorCST->getValue().isNegative()) {
6366 ICI.setOperand(0, CompareVal);
6367 AddToWorkList(LHSI);
6368 return &ICI;
6369 }
6370
6371 // Was the old condition true if the operand is positive?
6372 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6373
6374 // If so, the new one isn't.
6375 isTrueIfPositive ^= true;
6376
6377 if (isTrueIfPositive)
6378 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6379 else
6380 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6381 }
6382 }
6383 break;
6384 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6385 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6386 LHSI->getOperand(0)->hasOneUse()) {
6387 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6388
6389 // If the LHS is an AND of a truncating cast, we can widen the
6390 // and/compare to be the input width without changing the value
6391 // produced, eliminating a cast.
6392 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6393 // We can do this transformation if either the AND constant does not
6394 // have its sign bit set or if it is an equality comparison.
6395 // Extending a relational comparison when we're checking the sign
6396 // bit would not work.
6397 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006398 (ICI.isEquality() ||
6399 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006400 uint32_t BitWidth =
6401 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6402 APInt NewCST = AndCST->getValue();
6403 NewCST.zext(BitWidth);
6404 APInt NewCI = RHSV;
6405 NewCI.zext(BitWidth);
6406 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006407 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006408 ConstantInt::get(NewCST),LHSI->getName());
6409 InsertNewInstBefore(NewAnd, ICI);
6410 return new ICmpInst(ICI.getPredicate(), NewAnd,
6411 ConstantInt::get(NewCI));
6412 }
6413 }
6414
6415 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6416 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6417 // happens a LOT in code produced by the C front-end, for bitfield
6418 // access.
6419 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6420 if (Shift && !Shift->isShift())
6421 Shift = 0;
6422
6423 ConstantInt *ShAmt;
6424 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6425 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6426 const Type *AndTy = AndCST->getType(); // Type of the and.
6427
6428 // We can fold this as long as we can't shift unknown bits
6429 // into the mask. This can only happen with signed shift
6430 // rights, as they sign-extend.
6431 if (ShAmt) {
6432 bool CanFold = Shift->isLogicalShift();
6433 if (!CanFold) {
6434 // To test for the bad case of the signed shr, see if any
6435 // of the bits shifted in could be tested after the mask.
6436 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6437 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6438
6439 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6440 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6441 AndCST->getValue()) == 0)
6442 CanFold = true;
6443 }
6444
6445 if (CanFold) {
6446 Constant *NewCst;
6447 if (Shift->getOpcode() == Instruction::Shl)
6448 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6449 else
6450 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6451
6452 // Check to see if we are shifting out any of the bits being
6453 // compared.
6454 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6455 // If we shifted bits out, the fold is not going to work out.
6456 // As a special case, check to see if this means that the
6457 // result is always true or false now.
6458 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6459 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6460 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6461 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6462 } else {
6463 ICI.setOperand(1, NewCst);
6464 Constant *NewAndCST;
6465 if (Shift->getOpcode() == Instruction::Shl)
6466 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6467 else
6468 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6469 LHSI->setOperand(1, NewAndCST);
6470 LHSI->setOperand(0, Shift->getOperand(0));
6471 AddToWorkList(Shift); // Shift is dead.
6472 AddUsesToWorkList(ICI);
6473 return &ICI;
6474 }
6475 }
6476 }
6477
6478 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6479 // preferable because it allows the C<<Y expression to be hoisted out
6480 // of a loop if Y is invariant and X is not.
6481 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6482 ICI.isEquality() && !Shift->isArithmeticShift() &&
6483 isa<Instruction>(Shift->getOperand(0))) {
6484 // Compute C << Y.
6485 Value *NS;
6486 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006487 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006488 Shift->getOperand(1), "tmp");
6489 } else {
6490 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006491 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006492 Shift->getOperand(1), "tmp");
6493 }
6494 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6495
6496 // Compute X & (C << Y).
6497 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006498 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006499 InsertNewInstBefore(NewAnd, ICI);
6500
6501 ICI.setOperand(0, NewAnd);
6502 return &ICI;
6503 }
6504 }
6505 break;
6506
Chris Lattnera0141b92007-07-15 20:42:37 +00006507 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6508 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6509 if (!ShAmt) break;
6510
6511 uint32_t TypeBits = RHSV.getBitWidth();
6512
6513 // Check that the shift amount is in range. If not, don't perform
6514 // undefined shifts. When the shift is visited it will be
6515 // simplified.
6516 if (ShAmt->uge(TypeBits))
6517 break;
6518
6519 if (ICI.isEquality()) {
6520 // If we are comparing against bits always shifted out, the
6521 // comparison cannot succeed.
6522 Constant *Comp =
6523 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6524 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6525 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6526 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6527 return ReplaceInstUsesWith(ICI, Cst);
6528 }
6529
6530 if (LHSI->hasOneUse()) {
6531 // Otherwise strength reduce the shift into an and.
6532 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6533 Constant *Mask =
6534 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006535
Chris Lattnera0141b92007-07-15 20:42:37 +00006536 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006537 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006538 Mask, LHSI->getName()+".mask");
6539 Value *And = InsertNewInstBefore(AndI, ICI);
6540 return new ICmpInst(ICI.getPredicate(), And,
6541 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006542 }
6543 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006544
6545 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6546 bool TrueIfSigned = false;
6547 if (LHSI->hasOneUse() &&
6548 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6549 // (X << 31) <s 0 --> (X&1) != 0
6550 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6551 (TypeBits-ShAmt->getZExtValue()-1));
6552 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006553 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006554 Mask, LHSI->getName()+".mask");
6555 Value *And = InsertNewInstBefore(AndI, ICI);
6556
6557 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6558 And, Constant::getNullValue(And->getType()));
6559 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006560 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006561 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006562
6563 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006564 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006565 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006566 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006567 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006568
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006569 // Check that the shift amount is in range. If not, don't perform
6570 // undefined shifts. When the shift is visited it will be
6571 // simplified.
6572 uint32_t TypeBits = RHSV.getBitWidth();
6573 if (ShAmt->uge(TypeBits))
6574 break;
6575
6576 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006577
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006578 // If we are comparing against bits always shifted out, the
6579 // comparison cannot succeed.
6580 APInt Comp = RHSV << ShAmtVal;
6581 if (LHSI->getOpcode() == Instruction::LShr)
6582 Comp = Comp.lshr(ShAmtVal);
6583 else
6584 Comp = Comp.ashr(ShAmtVal);
6585
6586 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6587 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6588 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6589 return ReplaceInstUsesWith(ICI, Cst);
6590 }
6591
6592 // Otherwise, check to see if the bits shifted out are known to be zero.
6593 // If so, we can compare against the unshifted value:
6594 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006595 if (LHSI->hasOneUse() &&
6596 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006597 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6598 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6599 ConstantExpr::getShl(RHS, ShAmt));
6600 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006601
Evan Chengf30752c2008-04-23 00:38:06 +00006602 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006603 // Otherwise strength reduce the shift into an and.
6604 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6605 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006606
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006607 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006608 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006609 Mask, LHSI->getName()+".mask");
6610 Value *And = InsertNewInstBefore(AndI, ICI);
6611 return new ICmpInst(ICI.getPredicate(), And,
6612 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006613 }
6614 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006615 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006616
6617 case Instruction::SDiv:
6618 case Instruction::UDiv:
6619 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6620 // Fold this div into the comparison, producing a range check.
6621 // Determine, based on the divide type, what the range is being
6622 // checked. If there is an overflow on the low or high side, remember
6623 // it, otherwise compute the range [low, hi) bounding the new value.
6624 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006625 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6626 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6627 DivRHS))
6628 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006629 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006630
6631 case Instruction::Add:
6632 // Fold: icmp pred (add, X, C1), C2
6633
6634 if (!ICI.isEquality()) {
6635 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6636 if (!LHSC) break;
6637 const APInt &LHSV = LHSC->getValue();
6638
6639 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6640 .subtract(LHSV);
6641
6642 if (ICI.isSignedPredicate()) {
6643 if (CR.getLower().isSignBit()) {
6644 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6645 ConstantInt::get(CR.getUpper()));
6646 } else if (CR.getUpper().isSignBit()) {
6647 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6648 ConstantInt::get(CR.getLower()));
6649 }
6650 } else {
6651 if (CR.getLower().isMinValue()) {
6652 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6653 ConstantInt::get(CR.getUpper()));
6654 } else if (CR.getUpper().isMinValue()) {
6655 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6656 ConstantInt::get(CR.getLower()));
6657 }
6658 }
6659 }
6660 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006661 }
6662
6663 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6664 if (ICI.isEquality()) {
6665 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6666
6667 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6668 // the second operand is a constant, simplify a bit.
6669 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6670 switch (BO->getOpcode()) {
6671 case Instruction::SRem:
6672 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6673 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6674 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6675 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6676 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006677 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006678 BO->getName());
6679 InsertNewInstBefore(NewRem, ICI);
6680 return new ICmpInst(ICI.getPredicate(), NewRem,
6681 Constant::getNullValue(BO->getType()));
6682 }
6683 }
6684 break;
6685 case Instruction::Add:
6686 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6687 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6688 if (BO->hasOneUse())
6689 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6690 Subtract(RHS, BOp1C));
6691 } else if (RHSV == 0) {
6692 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6693 // efficiently invertible, or if the add has just this one use.
6694 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6695
6696 if (Value *NegVal = dyn_castNegVal(BOp1))
6697 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6698 else if (Value *NegVal = dyn_castNegVal(BOp0))
6699 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6700 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006701 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006702 InsertNewInstBefore(Neg, ICI);
6703 Neg->takeName(BO);
6704 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6705 }
6706 }
6707 break;
6708 case Instruction::Xor:
6709 // For the xor case, we can xor two constants together, eliminating
6710 // the explicit xor.
6711 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6712 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6713 ConstantExpr::getXor(RHS, BOC));
6714
6715 // FALLTHROUGH
6716 case Instruction::Sub:
6717 // Replace (([sub|xor] A, B) != 0) with (A != B)
6718 if (RHSV == 0)
6719 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6720 BO->getOperand(1));
6721 break;
6722
6723 case Instruction::Or:
6724 // If bits are being or'd in that are not present in the constant we
6725 // are comparing against, then the comparison could never succeed!
6726 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6727 Constant *NotCI = ConstantExpr::getNot(RHS);
6728 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6729 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6730 isICMP_NE));
6731 }
6732 break;
6733
6734 case Instruction::And:
6735 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6736 // If bits are being compared against that are and'd out, then the
6737 // comparison can never succeed!
6738 if ((RHSV & ~BOC->getValue()) != 0)
6739 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6740 isICMP_NE));
6741
6742 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6743 if (RHS == BOC && RHSV.isPowerOf2())
6744 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6745 ICmpInst::ICMP_NE, LHSI,
6746 Constant::getNullValue(RHS->getType()));
6747
6748 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6749 if (isSignBit(BOC)) {
6750 Value *X = BO->getOperand(0);
6751 Constant *Zero = Constant::getNullValue(X->getType());
6752 ICmpInst::Predicate pred = isICMP_NE ?
6753 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6754 return new ICmpInst(pred, X, Zero);
6755 }
6756
6757 // ((X & ~7) == 0) --> X < 8
6758 if (RHSV == 0 && isHighOnes(BOC)) {
6759 Value *X = BO->getOperand(0);
6760 Constant *NegX = ConstantExpr::getNeg(BOC);
6761 ICmpInst::Predicate pred = isICMP_NE ?
6762 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6763 return new ICmpInst(pred, X, NegX);
6764 }
6765 }
6766 default: break;
6767 }
6768 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6769 // Handle icmp {eq|ne} <intrinsic>, intcst.
6770 if (II->getIntrinsicID() == Intrinsic::bswap) {
6771 AddToWorkList(II);
6772 ICI.setOperand(0, II->getOperand(1));
6773 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6774 return &ICI;
6775 }
6776 }
6777 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006778 // If the LHS is a cast from an integral value of the same size,
6779 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006780 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6781 Value *CastOp = Cast->getOperand(0);
6782 const Type *SrcTy = CastOp->getType();
6783 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6784 if (SrcTy->isInteger() &&
6785 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6786 // If this is an unsigned comparison, try to make the comparison use
6787 // smaller constant values.
6788 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6789 // X u< 128 => X s> -1
6790 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6791 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6792 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6793 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6794 // X u> 127 => X s< 0
6795 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6796 Constant::getNullValue(SrcTy));
6797 }
6798 }
6799 }
6800 }
6801 return 0;
6802}
6803
6804/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6805/// We only handle extending casts so far.
6806///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006807Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6808 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006809 Value *LHSCIOp = LHSCI->getOperand(0);
6810 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006811 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006812 Value *RHSCIOp;
6813
Chris Lattner8c756c12007-05-05 22:41:33 +00006814 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6815 // integer type is the same size as the pointer type.
6816 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6817 getTargetData().getPointerSizeInBits() ==
6818 cast<IntegerType>(DestTy)->getBitWidth()) {
6819 Value *RHSOp = 0;
6820 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006821 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006822 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6823 RHSOp = RHSC->getOperand(0);
6824 // If the pointer types don't match, insert a bitcast.
6825 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006826 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006827 }
6828
6829 if (RHSOp)
6830 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6831 }
6832
6833 // The code below only handles extension cast instructions, so far.
6834 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006835 if (LHSCI->getOpcode() != Instruction::ZExt &&
6836 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006837 return 0;
6838
Reid Spencere4d87aa2006-12-23 06:05:41 +00006839 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6840 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006841
Reid Spencere4d87aa2006-12-23 06:05:41 +00006842 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006843 // Not an extension from the same type?
6844 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006845 if (RHSCIOp->getType() != LHSCIOp->getType())
6846 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006847
Nick Lewycky4189a532008-01-28 03:48:02 +00006848 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006849 // and the other is a zext), then we can't handle this.
6850 if (CI->getOpcode() != LHSCI->getOpcode())
6851 return 0;
6852
Nick Lewycky4189a532008-01-28 03:48:02 +00006853 // Deal with equality cases early.
6854 if (ICI.isEquality())
6855 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6856
6857 // A signed comparison of sign extended values simplifies into a
6858 // signed comparison.
6859 if (isSignedCmp && isSignedExt)
6860 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6861
6862 // The other three cases all fold into an unsigned comparison.
6863 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006864 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006865
Reid Spencere4d87aa2006-12-23 06:05:41 +00006866 // If we aren't dealing with a constant on the RHS, exit early
6867 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6868 if (!CI)
6869 return 0;
6870
6871 // Compute the constant that would happen if we truncated to SrcTy then
6872 // reextended to DestTy.
6873 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6874 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6875
6876 // If the re-extended constant didn't change...
6877 if (Res2 == CI) {
6878 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6879 // For example, we might have:
6880 // %A = sext short %X to uint
6881 // %B = icmp ugt uint %A, 1330
6882 // It is incorrect to transform this into
6883 // %B = icmp ugt short %X, 1330
6884 // because %A may have negative value.
6885 //
6886 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6887 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006888 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006889 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6890 else
6891 return 0;
6892 }
6893
6894 // The re-extended constant changed so the constant cannot be represented
6895 // in the shorter type. Consequently, we cannot emit a simple comparison.
6896
6897 // First, handle some easy cases. We know the result cannot be equal at this
6898 // point so handle the ICI.isEquality() cases
6899 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006900 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006901 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006902 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006903
6904 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6905 // should have been folded away previously and not enter in here.
6906 Value *Result;
6907 if (isSignedCmp) {
6908 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006909 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006910 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006911 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006912 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006913 } else {
6914 // We're performing an unsigned comparison.
6915 if (isSignedExt) {
6916 // We're performing an unsigned comp with a sign extended value.
6917 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006918 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006919 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6920 NegOne, ICI.getName()), ICI);
6921 } else {
6922 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006923 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006924 }
6925 }
6926
6927 // Finally, return the value computed.
6928 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6929 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6930 return ReplaceInstUsesWith(ICI, Result);
6931 } else {
6932 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6933 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6934 "ICmp should be folded!");
6935 if (Constant *CI = dyn_cast<Constant>(Result))
6936 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6937 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006938 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006939 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006940}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006941
Reid Spencer832254e2007-02-02 02:16:23 +00006942Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6943 return commonShiftTransforms(I);
6944}
6945
6946Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6947 return commonShiftTransforms(I);
6948}
6949
6950Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006951 if (Instruction *R = commonShiftTransforms(I))
6952 return R;
6953
6954 Value *Op0 = I.getOperand(0);
6955
6956 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6957 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6958 if (CSI->isAllOnesValue())
6959 return ReplaceInstUsesWith(I, CSI);
6960
6961 // See if we can turn a signed shr into an unsigned shr.
6962 if (MaskedValueIsZero(Op0,
6963 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006964 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006965
6966 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006967}
6968
6969Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6970 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006972
6973 // shl X, 0 == X and shr X, 0 == X
6974 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006975 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006976 Op0 == Constant::getNullValue(Op0->getType()))
6977 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006978
Reid Spencere4d87aa2006-12-23 06:05:41 +00006979 if (isa<UndefValue>(Op0)) {
6980 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006981 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006982 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6984 }
6985 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006986 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6987 return ReplaceInstUsesWith(I, Op0);
6988 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006990 }
6991
Chris Lattner2eefe512004-04-09 19:05:30 +00006992 // Try to fold constant and into select arguments.
6993 if (isa<Constant>(Op0))
6994 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006995 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006996 return R;
6997
Reid Spencerb83eb642006-10-20 07:07:24 +00006998 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006999 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7000 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007001 return 0;
7002}
7003
Reid Spencerb83eb642006-10-20 07:07:24 +00007004Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007005 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007006 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007007
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007008 // See if we can simplify any instructions used by the instruction whose sole
7009 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00007010 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7011 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
7012 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007013 KnownZero, KnownOne))
7014 return &I;
7015
Chris Lattner4d5542c2006-01-06 07:12:35 +00007016 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7017 // of a signed value.
7018 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007019 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007020 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007021 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7022 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007023 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007024 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007025 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007026 }
7027
7028 // ((X*C1) << C2) == (X * (C1 << C2))
7029 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7030 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7031 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007032 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007033 ConstantExpr::getShl(BOOp, Op1));
7034
7035 // Try to fold constant and into select arguments.
7036 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7037 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7038 return R;
7039 if (isa<PHINode>(Op0))
7040 if (Instruction *NV = FoldOpIntoPhi(I))
7041 return NV;
7042
Chris Lattner8999dd32007-12-22 09:07:47 +00007043 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7044 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7045 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7046 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7047 // place. Don't try to do this transformation in this case. Also, we
7048 // require that the input operand is a shift-by-constant so that we have
7049 // confidence that the shifts will get folded together. We could do this
7050 // xform in more cases, but it is unlikely to be profitable.
7051 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7052 isa<ConstantInt>(TrOp->getOperand(1))) {
7053 // Okay, we'll do this xform. Make the shift of shift.
7054 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007055 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007056 I.getName());
7057 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7058
7059 // For logical shifts, the truncation has the effect of making the high
7060 // part of the register be zeros. Emulate this by inserting an AND to
7061 // clear the top bits as needed. This 'and' will usually be zapped by
7062 // other xforms later if dead.
7063 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7064 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7065 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7066
7067 // The mask we constructed says what the trunc would do if occurring
7068 // between the shifts. We want to know the effect *after* the second
7069 // shift. We know that it is a logical shift by a constant, so adjust the
7070 // mask as appropriate.
7071 if (I.getOpcode() == Instruction::Shl)
7072 MaskV <<= Op1->getZExtValue();
7073 else {
7074 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7075 MaskV = MaskV.lshr(Op1->getZExtValue());
7076 }
7077
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007078 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007079 TI->getName());
7080 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7081
7082 // Return the value truncated to the interesting size.
7083 return new TruncInst(And, I.getType());
7084 }
7085 }
7086
Chris Lattner4d5542c2006-01-06 07:12:35 +00007087 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007088 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7089 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7090 Value *V1, *V2;
7091 ConstantInt *CC;
7092 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007093 default: break;
7094 case Instruction::Add:
7095 case Instruction::And:
7096 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007097 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007098 // These operators commute.
7099 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007100 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7101 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007102 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007103 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007104 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007105 Op0BO->getName());
7106 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007107 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007108 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007109 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007110 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007111 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007112 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007113 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007114 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007115
Chris Lattner150f12a2005-09-18 06:30:59 +00007116 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007117 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007118 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007119 match(Op0BOOp1,
7120 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007121 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7122 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007123 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007124 Op0BO->getOperand(0), Op1,
7125 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007126 InsertNewInstBefore(YS, I); // (Y << C)
7127 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007128 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007129 V1->getName()+".mask");
7130 InsertNewInstBefore(XM, I); // X & (CC << C)
7131
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007132 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007133 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007134 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007135
Reid Spencera07cb7d2007-02-02 14:41:37 +00007136 // FALL THROUGH.
7137 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007138 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007139 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7140 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007141 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007142 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007143 Op0BO->getOperand(1), Op1,
7144 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007145 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007146 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007147 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007148 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007149 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007150 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007151 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007152 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007153 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007154
Chris Lattner13d4ab42006-05-31 21:14:00 +00007155 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007156 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7157 match(Op0BO->getOperand(0),
7158 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007159 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007160 cast<BinaryOperator>(Op0BO->getOperand(0))
7161 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007162 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007163 Op0BO->getOperand(1), Op1,
7164 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007165 InsertNewInstBefore(YS, I); // (Y << C)
7166 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007167 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007168 V1->getName()+".mask");
7169 InsertNewInstBefore(XM, I); // X & (CC << C)
7170
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007171 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007172 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007173
Chris Lattner11021cb2005-09-18 05:12:10 +00007174 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007175 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007176 }
7177
7178
7179 // If the operand is an bitwise operator with a constant RHS, and the
7180 // shift is the only use, we can pull it out of the shift.
7181 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7182 bool isValid = true; // Valid only for And, Or, Xor
7183 bool highBitSet = false; // Transform if high bit of constant set?
7184
7185 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007186 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007187 case Instruction::Add:
7188 isValid = isLeftShift;
7189 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007190 case Instruction::Or:
7191 case Instruction::Xor:
7192 highBitSet = false;
7193 break;
7194 case Instruction::And:
7195 highBitSet = true;
7196 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007197 }
7198
7199 // If this is a signed shift right, and the high bit is modified
7200 // by the logical operation, do not perform the transformation.
7201 // The highBitSet boolean indicates the value of the high bit of
7202 // the constant which would cause it to be modified for this
7203 // operation.
7204 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007205 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007206 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007207
7208 if (isValid) {
7209 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7210
7211 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007212 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007213 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007214 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007215
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007216 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007217 NewRHS);
7218 }
7219 }
7220 }
7221 }
7222
Chris Lattnerad0124c2006-01-06 07:52:12 +00007223 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007224 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7225 if (ShiftOp && !ShiftOp->isShift())
7226 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007227
Reid Spencerb83eb642006-10-20 07:07:24 +00007228 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007229 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007230 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7231 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007232 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7233 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7234 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007235
Zhou Sheng4351c642007-04-02 08:20:41 +00007236 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007237 if (AmtSum > TypeBits)
7238 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007239
7240 const IntegerType *Ty = cast<IntegerType>(I.getType());
7241
7242 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007243 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007244 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007245 ConstantInt::get(Ty, AmtSum));
7246 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7247 I.getOpcode() == Instruction::AShr) {
7248 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007249 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007250 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7251 I.getOpcode() == Instruction::LShr) {
7252 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7253 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007254 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007255 InsertNewInstBefore(Shift, I);
7256
Zhou Shenge9e03f62007-03-28 15:02:20 +00007257 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007258 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007259 }
7260
Chris Lattnerb87056f2007-02-05 00:57:54 +00007261 // Okay, if we get here, one shift must be left, and the other shift must be
7262 // right. See if the amounts are equal.
7263 if (ShiftAmt1 == ShiftAmt2) {
7264 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7265 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007266 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007267 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007268 }
7269 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7270 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007271 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007272 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007273 }
7274 // We can simplify ((X << C) >>s C) into a trunc + sext.
7275 // NOTE: we could do this for any C, but that would make 'unusual' integer
7276 // types. For now, just stick to ones well-supported by the code
7277 // generators.
7278 const Type *SExtType = 0;
7279 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007280 case 1 :
7281 case 8 :
7282 case 16 :
7283 case 32 :
7284 case 64 :
7285 case 128:
7286 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7287 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007288 default: break;
7289 }
7290 if (SExtType) {
7291 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7292 InsertNewInstBefore(NewTrunc, I);
7293 return new SExtInst(NewTrunc, Ty);
7294 }
7295 // Otherwise, we can't handle it yet.
7296 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007297 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007298
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007299 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007300 if (I.getOpcode() == Instruction::Shl) {
7301 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7302 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007303 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007304 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007305 InsertNewInstBefore(Shift, I);
7306
Reid Spencer55702aa2007-03-25 21:11:44 +00007307 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007308 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007309 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007310
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007311 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007312 if (I.getOpcode() == Instruction::LShr) {
7313 assert(ShiftOp->getOpcode() == Instruction::Shl);
7314 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007315 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007316 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007317
Reid Spencerd5e30f02007-03-26 17:18:58 +00007318 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007319 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007320 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007321
7322 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7323 } else {
7324 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007325 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007326
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007327 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007328 if (I.getOpcode() == Instruction::Shl) {
7329 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7330 ShiftOp->getOpcode() == Instruction::AShr);
7331 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007332 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007333 ConstantInt::get(Ty, ShiftDiff));
7334 InsertNewInstBefore(Shift, I);
7335
Reid Spencer55702aa2007-03-25 21:11:44 +00007336 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007337 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007338 }
7339
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007340 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007341 if (I.getOpcode() == Instruction::LShr) {
7342 assert(ShiftOp->getOpcode() == Instruction::Shl);
7343 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007344 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007345 InsertNewInstBefore(Shift, I);
7346
Reid Spencer68d27cf2007-03-26 23:45:51 +00007347 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007348 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007349 }
7350
7351 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007352 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007353 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007354 return 0;
7355}
7356
Chris Lattnera1be5662002-05-02 17:06:02 +00007357
Chris Lattnercfd65102005-10-29 04:36:15 +00007358/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7359/// expression. If so, decompose it, returning some value X, such that Val is
7360/// X*Scale+Offset.
7361///
7362static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007363 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007364 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007365 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007366 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007367 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007368 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007369 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7370 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7371 if (I->getOpcode() == Instruction::Shl) {
7372 // This is a value scaled by '1 << the shift amt'.
7373 Scale = 1U << RHS->getZExtValue();
7374 Offset = 0;
7375 return I->getOperand(0);
7376 } else if (I->getOpcode() == Instruction::Mul) {
7377 // This value is scaled by 'RHS'.
7378 Scale = RHS->getZExtValue();
7379 Offset = 0;
7380 return I->getOperand(0);
7381 } else if (I->getOpcode() == Instruction::Add) {
7382 // We have X+C. Check to see if we really have (X*C2)+C1,
7383 // where C1 is divisible by C2.
7384 unsigned SubScale;
7385 Value *SubVal =
7386 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7387 Offset += RHS->getZExtValue();
7388 Scale = SubScale;
7389 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007390 }
7391 }
7392 }
7393
7394 // Otherwise, we can't look past this.
7395 Scale = 1;
7396 Offset = 0;
7397 return Val;
7398}
7399
7400
Chris Lattnerb3f83972005-10-24 06:03:58 +00007401/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7402/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007403Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007404 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007405 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007406
Chris Lattnerb53c2382005-10-24 06:22:12 +00007407 // Remove any uses of AI that are dead.
7408 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007409
Chris Lattnerb53c2382005-10-24 06:22:12 +00007410 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7411 Instruction *User = cast<Instruction>(*UI++);
7412 if (isInstructionTriviallyDead(User)) {
7413 while (UI != E && *UI == User)
7414 ++UI; // If this instruction uses AI more than once, don't break UI.
7415
Chris Lattnerb53c2382005-10-24 06:22:12 +00007416 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007417 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007418 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007419 }
7420 }
7421
Chris Lattnerb3f83972005-10-24 06:03:58 +00007422 // Get the type really allocated and the type casted to.
7423 const Type *AllocElTy = AI.getAllocatedType();
7424 const Type *CastElTy = PTy->getElementType();
7425 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007426
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007427 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7428 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007429 if (CastElTyAlign < AllocElTyAlign) return 0;
7430
Chris Lattner39387a52005-10-24 06:35:18 +00007431 // If the allocation has multiple uses, only promote it if we are strictly
7432 // increasing the alignment of the resultant allocation. If we keep it the
7433 // same, we open the door to infinite loops of various kinds.
7434 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7435
Duncan Sands514ab342007-11-01 20:53:16 +00007436 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7437 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007438 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007439
Chris Lattner455fcc82005-10-29 03:19:53 +00007440 // See if we can satisfy the modulus by pulling a scale out of the array
7441 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007442 unsigned ArraySizeScale;
7443 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007444 Value *NumElements = // See if the array size is a decomposable linear expr.
7445 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7446
Chris Lattner455fcc82005-10-29 03:19:53 +00007447 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7448 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007449 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7450 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007451
Chris Lattner455fcc82005-10-29 03:19:53 +00007452 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7453 Value *Amt = 0;
7454 if (Scale == 1) {
7455 Amt = NumElements;
7456 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007457 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007458 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7459 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007460 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007461 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007462 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007463 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007464 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007465 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007466 }
7467
Jeff Cohen86796be2007-04-04 16:58:57 +00007468 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7469 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007470 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007471 Amt = InsertNewInstBefore(Tmp, AI);
7472 }
7473
Chris Lattnerb3f83972005-10-24 06:03:58 +00007474 AllocationInst *New;
7475 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007476 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007477 else
Chris Lattner6934a042007-02-11 01:23:03 +00007478 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007479 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007480 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007481
7482 // If the allocation has multiple uses, insert a cast and change all things
7483 // that used it to use the new cast. This will also hack on CI, but it will
7484 // die soon.
7485 if (!AI.hasOneUse()) {
7486 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007487 // New is the allocation instruction, pointer typed. AI is the original
7488 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7489 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007490 InsertNewInstBefore(NewCast, AI);
7491 AI.replaceAllUsesWith(NewCast);
7492 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007493 return ReplaceInstUsesWith(CI, New);
7494}
7495
Chris Lattner70074e02006-05-13 02:06:03 +00007496/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007497/// and return it as type Ty without inserting any new casts and without
7498/// changing the computed value. This is used by code that tries to decide
7499/// whether promoting or shrinking integer operations to wider or smaller types
7500/// will allow us to eliminate a truncate or extend.
7501///
7502/// This is a truncation operation if Ty is smaller than V->getType(), or an
7503/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007504bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7505 unsigned CastOpc,
7506 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007507 // We can always evaluate constants in another type.
7508 if (isa<ConstantInt>(V))
7509 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007510
7511 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007512 if (!I) return false;
7513
7514 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007515
Chris Lattner951626b2007-08-02 06:11:14 +00007516 // If this is an extension or truncate, we can often eliminate it.
7517 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7518 // If this is a cast from the destination type, we can trivially eliminate
7519 // it, and this will remove a cast overall.
7520 if (I->getOperand(0)->getType() == Ty) {
7521 // If the first operand is itself a cast, and is eliminable, do not count
7522 // this as an eliminable cast. We would prefer to eliminate those two
7523 // casts first.
7524 if (!isa<CastInst>(I->getOperand(0)))
7525 ++NumCastsRemoved;
7526 return true;
7527 }
7528 }
7529
7530 // We can't extend or shrink something that has multiple uses: doing so would
7531 // require duplicating the instruction in general, which isn't profitable.
7532 if (!I->hasOneUse()) return false;
7533
Chris Lattner70074e02006-05-13 02:06:03 +00007534 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007535 case Instruction::Add:
7536 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007537 case Instruction::And:
7538 case Instruction::Or:
7539 case Instruction::Xor:
7540 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007541 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7542 NumCastsRemoved) &&
7543 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7544 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007545
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007546 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007547 // A multiply can be truncated by truncating its operands.
7548 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7549 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7550 NumCastsRemoved) &&
7551 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7552 NumCastsRemoved);
7553
Chris Lattner46b96052006-11-29 07:18:39 +00007554 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007555 // If we are truncating the result of this SHL, and if it's a shift of a
7556 // constant amount, we can always perform a SHL in a smaller type.
7557 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007558 uint32_t BitWidth = Ty->getBitWidth();
7559 if (BitWidth < OrigTy->getBitWidth() &&
7560 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007561 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7562 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007563 }
7564 break;
7565 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007566 // If this is a truncate of a logical shr, we can truncate it to a smaller
7567 // lshr iff we know that the bits we would otherwise be shifting in are
7568 // already zeros.
7569 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007570 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7571 uint32_t BitWidth = Ty->getBitWidth();
7572 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007573 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007574 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
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 }
Chris Lattner46b96052006-11-29 07:18:39 +00007580 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007581 case Instruction::ZExt:
7582 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007583 case Instruction::Trunc:
7584 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007585 // can safely replace it. Note that replacing it does not reduce the number
7586 // of casts in the input.
7587 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007588 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007589
Reid Spencer3da59db2006-11-27 01:05:10 +00007590 break;
7591 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007592 // TODO: Can handle more cases here.
7593 break;
7594 }
7595
7596 return false;
7597}
7598
7599/// EvaluateInDifferentType - Given an expression that
7600/// CanEvaluateInDifferentType returns true for, actually insert the code to
7601/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007602Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007603 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007604 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007605 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007606
7607 // Otherwise, it must be an instruction.
7608 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007609 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007610 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007611 case Instruction::Add:
7612 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007613 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007614 case Instruction::And:
7615 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007616 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007617 case Instruction::AShr:
7618 case Instruction::LShr:
7619 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007620 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007621 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007622 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007623 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007624 break;
7625 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007626 case Instruction::Trunc:
7627 case Instruction::ZExt:
7628 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007629 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007630 // just return the source. There's no need to insert it because it is not
7631 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007632 if (I->getOperand(0)->getType() == Ty)
7633 return I->getOperand(0);
7634
Chris Lattner951626b2007-08-02 06:11:14 +00007635 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007636 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007637 Ty, I->getName());
7638 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007639 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007640 // TODO: Can handle more cases here.
7641 assert(0 && "Unreachable!");
7642 break;
7643 }
7644
7645 return InsertNewInstBefore(Res, *I);
7646}
7647
Reid Spencer3da59db2006-11-27 01:05:10 +00007648/// @brief Implement the transforms common to all CastInst visitors.
7649Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007650 Value *Src = CI.getOperand(0);
7651
Dan Gohman23d9d272007-05-11 21:10:54 +00007652 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007653 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007654 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007655 if (Instruction::CastOps opc =
7656 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7657 // The first cast (CSrc) is eliminable so we need to fix up or replace
7658 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007659 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007660 }
7661 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007662
Reid Spencer3da59db2006-11-27 01:05:10 +00007663 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007664 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7665 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7666 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007667
7668 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007669 if (isa<PHINode>(Src))
7670 if (Instruction *NV = FoldOpIntoPhi(CI))
7671 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007672
Reid Spencer3da59db2006-11-27 01:05:10 +00007673 return 0;
7674}
7675
Chris Lattnerd3e28342007-04-27 17:44:50 +00007676/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7677Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7678 Value *Src = CI.getOperand(0);
7679
Chris Lattnerd3e28342007-04-27 17:44:50 +00007680 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007681 // If casting the result of a getelementptr instruction with no offset, turn
7682 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007683 if (GEP->hasAllZeroIndices()) {
7684 // Changing the cast operand is usually not a good idea but it is safe
7685 // here because the pointer operand is being replaced with another
7686 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007687 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007688 CI.setOperand(0, GEP->getOperand(0));
7689 return &CI;
7690 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007691
7692 // If the GEP has a single use, and the base pointer is a bitcast, and the
7693 // GEP computes a constant offset, see if we can convert these three
7694 // instructions into fewer. This typically happens with unions and other
7695 // non-type-safe code.
7696 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7697 if (GEP->hasAllConstantIndices()) {
7698 // We are guaranteed to get a constant from EmitGEPOffset.
7699 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7700 int64_t Offset = OffsetV->getSExtValue();
7701
7702 // Get the base pointer input of the bitcast, and the type it points to.
7703 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7704 const Type *GEPIdxTy =
7705 cast<PointerType>(OrigBase->getType())->getElementType();
7706 if (GEPIdxTy->isSized()) {
7707 SmallVector<Value*, 8> NewIndices;
7708
Chris Lattnerc42e2262007-05-05 01:59:31 +00007709 // Start with the index over the outer type. Note that the type size
7710 // might be zero (even if the offset isn't zero) if the indexed type
7711 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007712 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007713 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007714 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007715 FirstIdx = Offset/TySize;
7716 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007717
Chris Lattnerc42e2262007-05-05 01:59:31 +00007718 // Handle silly modulus not returning values values [0..TySize).
7719 if (Offset < 0) {
7720 --FirstIdx;
7721 Offset += TySize;
7722 assert(Offset >= 0);
7723 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007724 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007725 }
7726
7727 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007728
7729 // Index into the types. If we fail, set OrigBase to null.
7730 while (Offset) {
7731 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7732 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007733 if (Offset < (int64_t)SL->getSizeInBytes()) {
7734 unsigned Elt = SL->getElementContainingOffset(Offset);
7735 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007736
Chris Lattner6b6aef82007-05-15 00:16:00 +00007737 Offset -= SL->getElementOffset(Elt);
7738 GEPIdxTy = STy->getElementType(Elt);
7739 } else {
7740 // Otherwise, we can't index into this, bail out.
7741 Offset = 0;
7742 OrigBase = 0;
7743 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007744 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7745 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007746 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007747 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7748 Offset %= EltSize;
7749 } else {
7750 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7751 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007752 GEPIdxTy = STy->getElementType();
7753 } else {
7754 // Otherwise, we can't index into this, bail out.
7755 Offset = 0;
7756 OrigBase = 0;
7757 }
7758 }
7759 if (OrigBase) {
7760 // If we were able to index down into an element, create the GEP
7761 // and bitcast the result. This eliminates one bitcast, potentially
7762 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007763 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7764 NewIndices.begin(),
7765 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007766 InsertNewInstBefore(NGEP, CI);
7767 NGEP->takeName(GEP);
7768
Chris Lattner9bc14642007-04-28 00:57:34 +00007769 if (isa<BitCastInst>(CI))
7770 return new BitCastInst(NGEP, CI.getType());
7771 assert(isa<PtrToIntInst>(CI));
7772 return new PtrToIntInst(NGEP, CI.getType());
7773 }
7774 }
7775 }
7776 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007777 }
7778
7779 return commonCastTransforms(CI);
7780}
7781
7782
7783
Chris Lattnerc739cd62007-03-03 05:27:34 +00007784/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7785/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007786/// cases.
7787/// @brief Implement the transforms common to CastInst with integer operands
7788Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7789 if (Instruction *Result = commonCastTransforms(CI))
7790 return Result;
7791
7792 Value *Src = CI.getOperand(0);
7793 const Type *SrcTy = Src->getType();
7794 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007795 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7796 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007797
Reid Spencer3da59db2006-11-27 01:05:10 +00007798 // See if we can simplify any instructions used by the LHS whose sole
7799 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007800 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7801 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007802 KnownZero, KnownOne))
7803 return &CI;
7804
7805 // If the source isn't an instruction or has more than one use then we
7806 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007807 Instruction *SrcI = dyn_cast<Instruction>(Src);
7808 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007809 return 0;
7810
Chris Lattnerc739cd62007-03-03 05:27:34 +00007811 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007812 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007813 if (!isa<BitCastInst>(CI) &&
7814 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007815 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007816 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007817 // eliminates the cast, so it is always a win. If this is a zero-extension,
7818 // we need to do an AND to maintain the clear top-part of the computation,
7819 // so we require that the input have eliminated at least one cast. If this
7820 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007821 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007822 bool DoXForm;
7823 switch (CI.getOpcode()) {
7824 default:
7825 // All the others use floating point so we shouldn't actually
7826 // get here because of the check above.
7827 assert(0 && "Unknown cast type");
7828 case Instruction::Trunc:
7829 DoXForm = true;
7830 break;
7831 case Instruction::ZExt:
7832 DoXForm = NumCastsRemoved >= 1;
7833 break;
7834 case Instruction::SExt:
7835 DoXForm = NumCastsRemoved >= 2;
7836 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007837 }
7838
7839 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007840 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7841 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007842 assert(Res->getType() == DestTy);
7843 switch (CI.getOpcode()) {
7844 default: assert(0 && "Unknown cast type!");
7845 case Instruction::Trunc:
7846 case Instruction::BitCast:
7847 // Just replace this cast with the result.
7848 return ReplaceInstUsesWith(CI, Res);
7849 case Instruction::ZExt: {
7850 // We need to emit an AND to clear the high bits.
7851 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007852 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7853 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007854 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007855 }
7856 case Instruction::SExt:
7857 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007858 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007859 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7860 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007861 }
7862 }
7863 }
7864
7865 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7866 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7867
7868 switch (SrcI->getOpcode()) {
7869 case Instruction::Add:
7870 case Instruction::Mul:
7871 case Instruction::And:
7872 case Instruction::Or:
7873 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007874 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007875 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7876 // Don't insert two casts if they cannot be eliminated. We allow
7877 // two casts to be inserted if the sizes are the same. This could
7878 // only be converting signedness, which is a noop.
7879 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007880 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7881 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007882 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007883 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7884 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007885 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007886 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007887 }
7888 }
7889
7890 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7891 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7892 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007893 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007894 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007895 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007896 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007897 }
7898 break;
7899 case Instruction::SDiv:
7900 case Instruction::UDiv:
7901 case Instruction::SRem:
7902 case Instruction::URem:
7903 // If we are just changing the sign, rewrite.
7904 if (DestBitSize == SrcBitSize) {
7905 // Don't insert two casts if they cannot be eliminated. We allow
7906 // two casts to be inserted if the sizes are the same. This could
7907 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007908 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7909 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007910 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7911 Op0, DestTy, SrcI);
7912 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7913 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007914 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007915 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7916 }
7917 }
7918 break;
7919
7920 case Instruction::Shl:
7921 // Allow changing the sign of the source operand. Do not allow
7922 // changing the size of the shift, UNLESS the shift amount is a
7923 // constant. We must not change variable sized shifts to a smaller
7924 // size, because it is undefined to shift more bits out than exist
7925 // in the value.
7926 if (DestBitSize == SrcBitSize ||
7927 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007928 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7929 Instruction::BitCast : Instruction::Trunc);
7930 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007931 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007932 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007933 }
7934 break;
7935 case Instruction::AShr:
7936 // If this is a signed shr, and if all bits shifted in are about to be
7937 // truncated off, turn it into an unsigned shr to allow greater
7938 // simplifications.
7939 if (DestBitSize < SrcBitSize &&
7940 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007941 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007942 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7943 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007944 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007945 }
7946 }
7947 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007948 }
7949 return 0;
7950}
7951
Chris Lattner8a9f5712007-04-11 06:57:46 +00007952Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007953 if (Instruction *Result = commonIntCastTransforms(CI))
7954 return Result;
7955
7956 Value *Src = CI.getOperand(0);
7957 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007958 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7959 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007960
7961 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7962 switch (SrcI->getOpcode()) {
7963 default: break;
7964 case Instruction::LShr:
7965 // We can shrink lshr to something smaller if we know the bits shifted in
7966 // are already zeros.
7967 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007968 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007969
7970 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007971 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007972 Value* SrcIOp0 = SrcI->getOperand(0);
7973 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007974 if (ShAmt >= DestBitWidth) // All zeros.
7975 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7976
7977 // Okay, we can shrink this. Truncate the input, then return a new
7978 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007979 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7980 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7981 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007982 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007983 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007984 } else { // This is a variable shr.
7985
7986 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7987 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7988 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007989 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007990 Value *One = ConstantInt::get(SrcI->getType(), 1);
7991
Reid Spencer832254e2007-02-02 02:16:23 +00007992 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007993 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007994 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007995 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007996 SrcI->getOperand(0),
7997 "tmp"), CI);
7998 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007999 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00008000 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008001 }
8002 break;
8003 }
8004 }
8005
8006 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008007}
8008
Evan Chengb98a10e2008-03-24 00:21:34 +00008009/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8010/// in order to eliminate the icmp.
8011Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8012 bool DoXform) {
8013 // If we are just checking for a icmp eq of a single bit and zext'ing it
8014 // to an integer, then shift the bit to the appropriate place and then
8015 // cast to integer to avoid the comparison.
8016 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8017 const APInt &Op1CV = Op1C->getValue();
8018
8019 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8020 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8021 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8022 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8023 if (!DoXform) return ICI;
8024
8025 Value *In = ICI->getOperand(0);
8026 Value *Sh = ConstantInt::get(In->getType(),
8027 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008028 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008029 In->getName()+".lobit"),
8030 CI);
8031 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008032 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008033 false/*ZExt*/, "tmp", &CI);
8034
8035 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8036 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008037 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008038 In->getName()+".not"),
8039 CI);
8040 }
8041
8042 return ReplaceInstUsesWith(CI, In);
8043 }
8044
8045
8046
8047 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8048 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8049 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8050 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8051 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8052 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8053 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8054 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8055 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8056 // This only works for EQ and NE
8057 ICI->isEquality()) {
8058 // If Op1C some other power of two, convert:
8059 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8060 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8061 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8062 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8063
8064 APInt KnownZeroMask(~KnownZero);
8065 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8066 if (!DoXform) return ICI;
8067
8068 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8069 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8070 // (X&4) == 2 --> false
8071 // (X&4) != 2 --> true
8072 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8073 Res = ConstantExpr::getZExt(Res, CI.getType());
8074 return ReplaceInstUsesWith(CI, Res);
8075 }
8076
8077 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8078 Value *In = ICI->getOperand(0);
8079 if (ShiftAmt) {
8080 // Perform a logical shr by shiftamt.
8081 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008082 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008083 ConstantInt::get(In->getType(), ShiftAmt),
8084 In->getName()+".lobit"), CI);
8085 }
8086
8087 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8088 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008089 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008090 InsertNewInstBefore(cast<Instruction>(In), CI);
8091 }
8092
8093 if (CI.getType() == In->getType())
8094 return ReplaceInstUsesWith(CI, In);
8095 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008096 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008097 }
8098 }
8099 }
8100
8101 return 0;
8102}
8103
Chris Lattner8a9f5712007-04-11 06:57:46 +00008104Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008105 // If one of the common conversion will work ..
8106 if (Instruction *Result = commonIntCastTransforms(CI))
8107 return Result;
8108
8109 Value *Src = CI.getOperand(0);
8110
8111 // If this is a cast of a cast
8112 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008113 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8114 // types and if the sizes are just right we can convert this into a logical
8115 // 'and' which will be much cheaper than the pair of casts.
8116 if (isa<TruncInst>(CSrc)) {
8117 // Get the sizes of the types involved
8118 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008119 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8120 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8121 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008122 // If we're actually extending zero bits and the trunc is a no-op
8123 if (MidSize < DstSize && SrcSize == DstSize) {
8124 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008125 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008126 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008127 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008128 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008129 // Unfortunately, if the type changed, we need to cast it back.
8130 if (And->getType() != CI.getType()) {
8131 And->setName(CSrc->getName()+".mask");
8132 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008133 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008134 }
8135 return And;
8136 }
8137 }
8138 }
8139
Evan Chengb98a10e2008-03-24 00:21:34 +00008140 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8141 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008142
Evan Chengb98a10e2008-03-24 00:21:34 +00008143 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8144 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8145 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8146 // of the (zext icmp) will be transformed.
8147 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8148 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8149 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8150 (transformZExtICmp(LHS, CI, false) ||
8151 transformZExtICmp(RHS, CI, false))) {
8152 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8153 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008154 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008155 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008156 }
8157
Reid Spencer3da59db2006-11-27 01:05:10 +00008158 return 0;
8159}
8160
Chris Lattner8a9f5712007-04-11 06:57:46 +00008161Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008162 if (Instruction *I = commonIntCastTransforms(CI))
8163 return I;
8164
Chris Lattner8a9f5712007-04-11 06:57:46 +00008165 Value *Src = CI.getOperand(0);
8166
8167 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8168 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8169 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8170 // If we are just checking for a icmp eq of a single bit and zext'ing it
8171 // to an integer, then shift the bit to the appropriate place and then
8172 // cast to integer to avoid the comparison.
8173 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8174 const APInt &Op1CV = Op1C->getValue();
8175
8176 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8177 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8178 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8179 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8180 Value *In = ICI->getOperand(0);
8181 Value *Sh = ConstantInt::get(In->getType(),
8182 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008183 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008184 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008185 CI);
8186 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008187 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008188 true/*SExt*/, "tmp", &CI);
8189
8190 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008191 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008192 In->getName()+".not"), CI);
8193
8194 return ReplaceInstUsesWith(CI, In);
8195 }
8196 }
8197 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008198
8199 // See if the value being truncated is already sign extended. If so, just
8200 // eliminate the trunc/sext pair.
8201 if (getOpcode(Src) == Instruction::Trunc) {
8202 Value *Op = cast<User>(Src)->getOperand(0);
8203 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8204 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8205 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8206 unsigned NumSignBits = ComputeNumSignBits(Op);
8207
8208 if (OpBits == DestBits) {
8209 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8210 // bits, it is already ready.
8211 if (NumSignBits > DestBits-MidBits)
8212 return ReplaceInstUsesWith(CI, Op);
8213 } else if (OpBits < DestBits) {
8214 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8215 // bits, just sext from i32.
8216 if (NumSignBits > OpBits-MidBits)
8217 return new SExtInst(Op, CI.getType(), "tmp");
8218 } else {
8219 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8220 // bits, just truncate to i32.
8221 if (NumSignBits > OpBits-MidBits)
8222 return new TruncInst(Op, CI.getType(), "tmp");
8223 }
8224 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008225
Chris Lattnerba417832007-04-11 06:12:58 +00008226 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008227}
8228
Chris Lattnerb7530652008-01-27 05:29:54 +00008229/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8230/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008231static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008232 APFloat F = CFP->getValueAPF();
8233 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008234 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008235 return 0;
8236}
8237
8238/// LookThroughFPExtensions - If this is an fp extension instruction, look
8239/// through it until we get the source value.
8240static Value *LookThroughFPExtensions(Value *V) {
8241 if (Instruction *I = dyn_cast<Instruction>(V))
8242 if (I->getOpcode() == Instruction::FPExt)
8243 return LookThroughFPExtensions(I->getOperand(0));
8244
8245 // If this value is a constant, return the constant in the smallest FP type
8246 // that can accurately represent it. This allows us to turn
8247 // (float)((double)X+2.0) into x+2.0f.
8248 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8249 if (CFP->getType() == Type::PPC_FP128Ty)
8250 return V; // No constant folding of this.
8251 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008252 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008253 return V;
8254 if (CFP->getType() == Type::DoubleTy)
8255 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008256 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008257 return V;
8258 // Don't try to shrink to various long double types.
8259 }
8260
8261 return V;
8262}
8263
8264Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8265 if (Instruction *I = commonCastTransforms(CI))
8266 return I;
8267
8268 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8269 // smaller than the destination type, we can eliminate the truncate by doing
8270 // the add as the smaller type. This applies to add/sub/mul/div as well as
8271 // many builtins (sqrt, etc).
8272 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8273 if (OpI && OpI->hasOneUse()) {
8274 switch (OpI->getOpcode()) {
8275 default: break;
8276 case Instruction::Add:
8277 case Instruction::Sub:
8278 case Instruction::Mul:
8279 case Instruction::FDiv:
8280 case Instruction::FRem:
8281 const Type *SrcTy = OpI->getType();
8282 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8283 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8284 if (LHSTrunc->getType() != SrcTy &&
8285 RHSTrunc->getType() != SrcTy) {
8286 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8287 // If the source types were both smaller than the destination type of
8288 // the cast, do this xform.
8289 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8290 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8291 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8292 CI.getType(), CI);
8293 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8294 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008295 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008296 }
8297 }
8298 break;
8299 }
8300 }
8301 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008302}
8303
8304Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8305 return commonCastTransforms(CI);
8306}
8307
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008308Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8309 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8310 // mantissa to accurately represent all values of X. For example, do not
8311 // do this with i64->float->i64.
8312 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8313 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8314 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008315 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008316 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8317
8318 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008319}
8320
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008321Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8322 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8323 // mantissa to accurately represent all values of X. For example, do not
8324 // do this with i64->float->i64.
8325 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8326 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8327 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008328 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008329 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8330
8331 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008332}
8333
8334Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8335 return commonCastTransforms(CI);
8336}
8337
8338Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8339 return commonCastTransforms(CI);
8340}
8341
8342Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008343 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008344}
8345
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008346Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8347 if (Instruction *I = commonCastTransforms(CI))
8348 return I;
8349
8350 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8351 if (!DestPointee->isSized()) return 0;
8352
8353 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8354 ConstantInt *Cst;
8355 Value *X;
8356 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8357 m_ConstantInt(Cst)))) {
8358 // If the source and destination operands have the same type, see if this
8359 // is a single-index GEP.
8360 if (X->getType() == CI.getType()) {
8361 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008362 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008363
8364 // Convert the constant to intptr type.
8365 APInt Offset = Cst->getValue();
8366 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8367
8368 // If Offset is evenly divisible by Size, we can do this xform.
8369 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8370 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008371 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008372 }
8373 }
8374 // TODO: Could handle other cases, e.g. where add is indexing into field of
8375 // struct etc.
8376 } else if (CI.getOperand(0)->hasOneUse() &&
8377 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8378 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8379 // "inttoptr+GEP" instead of "add+intptr".
8380
8381 // Get the size of the pointee type.
8382 uint64_t Size = TD->getABITypeSize(DestPointee);
8383
8384 // Convert the constant to intptr type.
8385 APInt Offset = Cst->getValue();
8386 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8387
8388 // If Offset is evenly divisible by Size, we can do this xform.
8389 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8390 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8391
8392 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8393 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008394 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008395 }
8396 }
8397 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008398}
8399
Chris Lattnerd3e28342007-04-27 17:44:50 +00008400Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008401 // If the operands are integer typed then apply the integer transforms,
8402 // otherwise just apply the common ones.
8403 Value *Src = CI.getOperand(0);
8404 const Type *SrcTy = Src->getType();
8405 const Type *DestTy = CI.getType();
8406
Chris Lattner42a75512007-01-15 02:27:26 +00008407 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008408 if (Instruction *Result = commonIntCastTransforms(CI))
8409 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008410 } else if (isa<PointerType>(SrcTy)) {
8411 if (Instruction *I = commonPointerCastTransforms(CI))
8412 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008413 } else {
8414 if (Instruction *Result = commonCastTransforms(CI))
8415 return Result;
8416 }
8417
8418
8419 // Get rid of casts from one type to the same type. These are useless and can
8420 // be replaced by the operand.
8421 if (DestTy == Src->getType())
8422 return ReplaceInstUsesWith(CI, Src);
8423
Reid Spencer3da59db2006-11-27 01:05:10 +00008424 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008425 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8426 const Type *DstElTy = DstPTy->getElementType();
8427 const Type *SrcElTy = SrcPTy->getElementType();
8428
Nate Begeman83ad90a2008-03-31 00:22:16 +00008429 // If the address spaces don't match, don't eliminate the bitcast, which is
8430 // required for changing types.
8431 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8432 return 0;
8433
Chris Lattnerd3e28342007-04-27 17:44:50 +00008434 // If we are casting a malloc or alloca to a pointer to a type of the same
8435 // size, rewrite the allocation instruction to allocate the "right" type.
8436 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8437 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8438 return V;
8439
Chris Lattnerd717c182007-05-05 22:32:24 +00008440 // If the source and destination are pointers, and this cast is equivalent
8441 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008442 // This can enhance SROA and other transforms that want type-safe pointers.
8443 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8444 unsigned NumZeros = 0;
8445 while (SrcElTy != DstElTy &&
8446 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8447 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8448 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8449 ++NumZeros;
8450 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008451
Chris Lattnerd3e28342007-04-27 17:44:50 +00008452 // If we found a path from the src to dest, create the getelementptr now.
8453 if (SrcElTy == DstElTy) {
8454 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008455 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8456 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008458 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008459
Reid Spencer3da59db2006-11-27 01:05:10 +00008460 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8461 if (SVI->hasOneUse()) {
8462 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8463 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008464 if (isa<VectorType>(DestTy) &&
8465 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008466 SVI->getType()->getNumElements()) {
8467 CastInst *Tmp;
8468 // If either of the operands is a cast from CI.getType(), then
8469 // evaluating the shuffle in the casted destination's type will allow
8470 // us to eliminate at least one cast.
8471 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8472 Tmp->getOperand(0)->getType() == DestTy) ||
8473 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8474 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008475 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8476 SVI->getOperand(0), DestTy, &CI);
8477 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8478 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008479 // Return a new shuffle vector. Use the same element ID's, as we
8480 // know the vector types match #elts.
8481 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008482 }
8483 }
8484 }
8485 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008486 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008487}
8488
Chris Lattnere576b912004-04-09 23:46:01 +00008489/// GetSelectFoldableOperands - We want to turn code that looks like this:
8490/// %C = or %A, %B
8491/// %D = select %cond, %C, %A
8492/// into:
8493/// %C = select %cond, %B, 0
8494/// %D = or %A, %C
8495///
8496/// Assuming that the specified instruction is an operand to the select, return
8497/// a bitmask indicating which operands of this instruction are foldable if they
8498/// equal the other incoming value of the select.
8499///
8500static unsigned GetSelectFoldableOperands(Instruction *I) {
8501 switch (I->getOpcode()) {
8502 case Instruction::Add:
8503 case Instruction::Mul:
8504 case Instruction::And:
8505 case Instruction::Or:
8506 case Instruction::Xor:
8507 return 3; // Can fold through either operand.
8508 case Instruction::Sub: // Can only fold on the amount subtracted.
8509 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008510 case Instruction::LShr:
8511 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008512 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008513 default:
8514 return 0; // Cannot fold
8515 }
8516}
8517
8518/// GetSelectFoldableConstant - For the same transformation as the previous
8519/// function, return the identity constant that goes into the select.
8520static Constant *GetSelectFoldableConstant(Instruction *I) {
8521 switch (I->getOpcode()) {
8522 default: assert(0 && "This cannot happen!"); abort();
8523 case Instruction::Add:
8524 case Instruction::Sub:
8525 case Instruction::Or:
8526 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008527 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008528 case Instruction::LShr:
8529 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008530 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008531 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008532 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008533 case Instruction::Mul:
8534 return ConstantInt::get(I->getType(), 1);
8535 }
8536}
8537
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008538/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8539/// have the same opcode and only one use each. Try to simplify this.
8540Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8541 Instruction *FI) {
8542 if (TI->getNumOperands() == 1) {
8543 // If this is a non-volatile load or a cast from the same type,
8544 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008545 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008546 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8547 return 0;
8548 } else {
8549 return 0; // unknown unary op.
8550 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008551
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008552 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008553 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8554 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008555 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008556 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008557 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008558 }
8559
Reid Spencer832254e2007-02-02 02:16:23 +00008560 // Only handle binary operators here.
8561 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008562 return 0;
8563
8564 // Figure out if the operations have any operands in common.
8565 Value *MatchOp, *OtherOpT, *OtherOpF;
8566 bool MatchIsOpZero;
8567 if (TI->getOperand(0) == FI->getOperand(0)) {
8568 MatchOp = TI->getOperand(0);
8569 OtherOpT = TI->getOperand(1);
8570 OtherOpF = FI->getOperand(1);
8571 MatchIsOpZero = true;
8572 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8573 MatchOp = TI->getOperand(1);
8574 OtherOpT = TI->getOperand(0);
8575 OtherOpF = FI->getOperand(0);
8576 MatchIsOpZero = false;
8577 } else if (!TI->isCommutative()) {
8578 return 0;
8579 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8580 MatchOp = TI->getOperand(0);
8581 OtherOpT = TI->getOperand(1);
8582 OtherOpF = FI->getOperand(0);
8583 MatchIsOpZero = true;
8584 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8585 MatchOp = TI->getOperand(1);
8586 OtherOpT = TI->getOperand(0);
8587 OtherOpF = FI->getOperand(1);
8588 MatchIsOpZero = true;
8589 } else {
8590 return 0;
8591 }
8592
8593 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008594 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8595 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008596 InsertNewInstBefore(NewSI, SI);
8597
8598 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8599 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008600 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008601 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008602 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008603 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008604 assert(0 && "Shouldn't get here");
8605 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008606}
8607
Chris Lattner3d69f462004-03-12 05:52:32 +00008608Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008609 Value *CondVal = SI.getCondition();
8610 Value *TrueVal = SI.getTrueValue();
8611 Value *FalseVal = SI.getFalseValue();
8612
8613 // select true, X, Y -> X
8614 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008615 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008616 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008617
8618 // select C, X, X -> X
8619 if (TrueVal == FalseVal)
8620 return ReplaceInstUsesWith(SI, TrueVal);
8621
Chris Lattnere87597f2004-10-16 18:11:37 +00008622 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8623 return ReplaceInstUsesWith(SI, FalseVal);
8624 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8625 return ReplaceInstUsesWith(SI, TrueVal);
8626 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8627 if (isa<Constant>(TrueVal))
8628 return ReplaceInstUsesWith(SI, TrueVal);
8629 else
8630 return ReplaceInstUsesWith(SI, FalseVal);
8631 }
8632
Reid Spencer4fe16d62007-01-11 18:21:29 +00008633 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008634 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008635 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008636 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008637 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008638 } else {
8639 // Change: A = select B, false, C --> A = and !B, C
8640 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008641 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008642 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008643 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008644 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008645 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008646 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008647 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008648 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008649 } else {
8650 // Change: A = select B, C, true --> A = or !B, C
8651 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008652 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008653 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008654 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008655 }
8656 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008657
8658 // select a, b, a -> a&b
8659 // select a, a, b -> a|b
8660 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008661 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008662 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008663 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008664 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008665
Chris Lattner2eefe512004-04-09 19:05:30 +00008666 // Selecting between two integer constants?
8667 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8668 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008669 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008670 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008671 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008672 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008673 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008674 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008675 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008676 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008677 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008678 }
Chris Lattnerba417832007-04-11 06:12:58 +00008679
8680 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008681
Reid Spencere4d87aa2006-12-23 06:05:41 +00008682 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008683
Reid Spencere4d87aa2006-12-23 06:05:41 +00008684 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008685 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008686 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008687 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008688 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008689 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008690 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008691 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008692 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008693 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008694 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008695 InsertNewInstBefore(SRA, SI);
8696
Reid Spencer3da59db2006-11-27 01:05:10 +00008697 // Finally, convert to the type of the select RHS. We figure out
8698 // if this requires a SExt, Trunc or BitCast based on the sizes.
8699 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008700 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8701 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008702 if (SRASize < SISize)
8703 opc = Instruction::SExt;
8704 else if (SRASize > SISize)
8705 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008706 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008707 }
8708 }
8709
8710
8711 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008712 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008713 // non-constant value, eliminate this whole mess. This corresponds to
8714 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008715 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008716 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008717 cast<Constant>(IC->getOperand(1))->isNullValue())
8718 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8719 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008720 isa<ConstantInt>(ICA->getOperand(1)) &&
8721 (ICA->getOperand(1) == TrueValC ||
8722 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008723 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8724 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008725 // know whether we have a icmp_ne or icmp_eq and whether the
8726 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008727 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008728 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008729 Value *V = ICA;
8730 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008731 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008732 Instruction::Xor, V, ICA->getOperand(1)), SI);
8733 return ReplaceInstUsesWith(SI, V);
8734 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008735 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008736 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008737
8738 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008739 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8740 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008741 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008742 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8743 // This is not safe in general for floating point:
8744 // consider X== -0, Y== +0.
8745 // It becomes safe if either operand is a nonzero constant.
8746 ConstantFP *CFPt, *CFPf;
8747 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8748 !CFPt->getValueAPF().isZero()) ||
8749 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8750 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008751 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008752 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008753 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008754 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008755 return ReplaceInstUsesWith(SI, TrueVal);
8756 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8757
Reid Spencere4d87aa2006-12-23 06:05:41 +00008758 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008759 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008760 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8761 // This is not safe in general for floating point:
8762 // consider X== -0, Y== +0.
8763 // It becomes safe if either operand is a nonzero constant.
8764 ConstantFP *CFPt, *CFPf;
8765 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8766 !CFPt->getValueAPF().isZero()) ||
8767 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8768 !CFPf->getValueAPF().isZero()))
8769 return ReplaceInstUsesWith(SI, FalseVal);
8770 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008771 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008772 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8773 return ReplaceInstUsesWith(SI, TrueVal);
8774 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8775 }
8776 }
8777
8778 // See if we are selecting two values based on a comparison of the two values.
8779 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8780 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8781 // Transform (X == Y) ? X : Y -> Y
8782 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8783 return ReplaceInstUsesWith(SI, FalseVal);
8784 // Transform (X != Y) ? X : Y -> X
8785 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8786 return ReplaceInstUsesWith(SI, TrueVal);
8787 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8788
8789 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8790 // Transform (X == Y) ? Y : X -> X
8791 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8792 return ReplaceInstUsesWith(SI, FalseVal);
8793 // Transform (X != Y) ? Y : X -> Y
8794 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008795 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008796 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8797 }
8798 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008799
Chris Lattner87875da2005-01-13 22:52:24 +00008800 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8801 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8802 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008803 Instruction *AddOp = 0, *SubOp = 0;
8804
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008805 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8806 if (TI->getOpcode() == FI->getOpcode())
8807 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8808 return IV;
8809
8810 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8811 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008812 if (TI->getOpcode() == Instruction::Sub &&
8813 FI->getOpcode() == Instruction::Add) {
8814 AddOp = FI; SubOp = TI;
8815 } else if (FI->getOpcode() == Instruction::Sub &&
8816 TI->getOpcode() == Instruction::Add) {
8817 AddOp = TI; SubOp = FI;
8818 }
8819
8820 if (AddOp) {
8821 Value *OtherAddOp = 0;
8822 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8823 OtherAddOp = AddOp->getOperand(1);
8824 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8825 OtherAddOp = AddOp->getOperand(0);
8826 }
8827
8828 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008829 // So at this point we know we have (Y -> OtherAddOp):
8830 // select C, (add X, Y), (sub X, Z)
8831 Value *NegVal; // Compute -Z
8832 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8833 NegVal = ConstantExpr::getNeg(C);
8834 } else {
8835 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008836 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008837 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008838
8839 Value *NewTrueOp = OtherAddOp;
8840 Value *NewFalseOp = NegVal;
8841 if (AddOp != TI)
8842 std::swap(NewTrueOp, NewFalseOp);
8843 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008844 SelectInst::Create(CondVal, NewTrueOp,
8845 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008846
8847 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008848 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008849 }
8850 }
8851 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008852
Chris Lattnere576b912004-04-09 23:46:01 +00008853 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008854 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008855 // See the comment above GetSelectFoldableOperands for a description of the
8856 // transformation we are doing here.
8857 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8858 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8859 !isa<Constant>(FalseVal))
8860 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8861 unsigned OpToFold = 0;
8862 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8863 OpToFold = 1;
8864 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8865 OpToFold = 2;
8866 }
8867
8868 if (OpToFold) {
8869 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008870 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008871 SelectInst::Create(SI.getCondition(),
8872 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008873 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008874 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008875 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008876 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008877 else {
8878 assert(0 && "Unknown instruction!!");
8879 }
8880 }
8881 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008882
Chris Lattnere576b912004-04-09 23:46:01 +00008883 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8884 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8885 !isa<Constant>(TrueVal))
8886 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8887 unsigned OpToFold = 0;
8888 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8889 OpToFold = 1;
8890 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8891 OpToFold = 2;
8892 }
8893
8894 if (OpToFold) {
8895 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008896 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008897 SelectInst::Create(SI.getCondition(), C,
8898 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008899 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008900 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008901 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008902 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008903 else
Chris Lattnere576b912004-04-09 23:46:01 +00008904 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008905 }
8906 }
8907 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008908
8909 if (BinaryOperator::isNot(CondVal)) {
8910 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8911 SI.setOperand(1, FalseVal);
8912 SI.setOperand(2, TrueVal);
8913 return &SI;
8914 }
8915
Chris Lattner3d69f462004-03-12 05:52:32 +00008916 return 0;
8917}
8918
Dan Gohmaneee962e2008-04-10 18:43:06 +00008919/// EnforceKnownAlignment - If the specified pointer points to an object that
8920/// we control, modify the object's alignment to PrefAlign. This isn't
8921/// often possible though. If alignment is important, a more reliable approach
8922/// is to simply align all global variables and allocation instructions to
8923/// their preferred alignment from the beginning.
8924///
8925static unsigned EnforceKnownAlignment(Value *V,
8926 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008927
Dan Gohmaneee962e2008-04-10 18:43:06 +00008928 User *U = dyn_cast<User>(V);
8929 if (!U) return Align;
8930
8931 switch (getOpcode(U)) {
8932 default: break;
8933 case Instruction::BitCast:
8934 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8935 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008936 // If all indexes are zero, it is just the alignment of the base pointer.
8937 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008938 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8939 if (!isa<Constant>(U->getOperand(i)) ||
8940 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008941 AllZeroOperands = false;
8942 break;
8943 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008944
8945 if (AllZeroOperands) {
8946 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008947 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008948 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008949 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008950 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008951 }
8952
8953 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8954 // If there is a large requested alignment and we can, bump up the alignment
8955 // of the global.
8956 if (!GV->isDeclaration()) {
8957 GV->setAlignment(PrefAlign);
8958 Align = PrefAlign;
8959 }
8960 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8961 // If there is a requested alignment and if this is an alloca, round up. We
8962 // don't do this for malloc, because some systems can't respect the request.
8963 if (isa<AllocaInst>(AI)) {
8964 AI->setAlignment(PrefAlign);
8965 Align = PrefAlign;
8966 }
8967 }
8968
8969 return Align;
8970}
8971
8972/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8973/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8974/// and it is more than the alignment of the ultimate object, see if we can
8975/// increase the alignment of the ultimate object, making this check succeed.
8976unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8977 unsigned PrefAlign) {
8978 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8979 sizeof(PrefAlign) * CHAR_BIT;
8980 APInt Mask = APInt::getAllOnesValue(BitWidth);
8981 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8982 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8983 unsigned TrailZ = KnownZero.countTrailingOnes();
8984 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8985
8986 if (PrefAlign > Align)
8987 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8988
8989 // We don't need to make any adjustment.
8990 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008991}
8992
Chris Lattnerf497b022008-01-13 23:50:23 +00008993Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008994 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8995 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008996 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8997 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8998
8999 if (CopyAlign < MinAlign) {
9000 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9001 return MI;
9002 }
9003
9004 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9005 // load/store.
9006 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9007 if (MemOpLength == 0) return 0;
9008
Chris Lattner37ac6082008-01-14 00:28:35 +00009009 // Source and destination pointer types are always "i8*" for intrinsic. See
9010 // if the size is something we can handle with a single primitive load/store.
9011 // A single load+store correctly handles overlapping memory in the memmove
9012 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009013 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009014 if (Size == 0) return MI; // Delete this mem transfer.
9015
9016 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009017 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009018
Chris Lattner37ac6082008-01-14 00:28:35 +00009019 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009020 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009021
9022 // Memcpy forces the use of i8* for the source and destination. That means
9023 // that if you're using memcpy to move one double around, you'll get a cast
9024 // from double* to i8*. We'd much rather use a double load+store rather than
9025 // an i64 load+store, here because this improves the odds that the source or
9026 // dest address will be promotable. See if we can find a better type than the
9027 // integer datatype.
9028 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9029 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9030 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9031 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9032 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009033 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009034 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9035 if (STy->getNumElements() == 1)
9036 SrcETy = STy->getElementType(0);
9037 else
9038 break;
9039 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9040 if (ATy->getNumElements() == 1)
9041 SrcETy = ATy->getElementType();
9042 else
9043 break;
9044 } else
9045 break;
9046 }
9047
Dan Gohman8f8e2692008-05-23 01:52:21 +00009048 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009049 NewPtrTy = PointerType::getUnqual(SrcETy);
9050 }
9051 }
9052
9053
Chris Lattnerf497b022008-01-13 23:50:23 +00009054 // If the memcpy/memmove provides better alignment info than we can
9055 // infer, use it.
9056 SrcAlign = std::max(SrcAlign, CopyAlign);
9057 DstAlign = std::max(DstAlign, CopyAlign);
9058
9059 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9060 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009061 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9062 InsertNewInstBefore(L, *MI);
9063 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9064
9065 // Set the size of the copy to 0, it will be deleted on the next iteration.
9066 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9067 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009068}
Chris Lattner3d69f462004-03-12 05:52:32 +00009069
Chris Lattner69ea9d22008-04-30 06:39:11 +00009070Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9071 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9072 if (MI->getAlignment()->getZExtValue() < Alignment) {
9073 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9074 return MI;
9075 }
9076
9077 // Extract the length and alignment and fill if they are constant.
9078 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9079 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9080 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9081 return 0;
9082 uint64_t Len = LenC->getZExtValue();
9083 Alignment = MI->getAlignment()->getZExtValue();
9084
9085 // If the length is zero, this is a no-op
9086 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9087
9088 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9089 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9090 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9091
9092 Value *Dest = MI->getDest();
9093 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9094
9095 // Alignment 0 is identity for alignment 1 for memset, but not store.
9096 if (Alignment == 0) Alignment = 1;
9097
9098 // Extract the fill value and store.
9099 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9100 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9101 Alignment), *MI);
9102
9103 // Set the size of the copy to 0, it will be deleted on the next iteration.
9104 MI->setLength(Constant::getNullValue(LenC->getType()));
9105 return MI;
9106 }
9107
9108 return 0;
9109}
9110
9111
Chris Lattner8b0ea312006-01-13 20:11:04 +00009112/// visitCallInst - CallInst simplification. This mostly only handles folding
9113/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9114/// the heavy lifting.
9115///
Chris Lattner9fe38862003-06-19 17:00:31 +00009116Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009117 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9118 if (!II) return visitCallSite(&CI);
9119
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009120 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9121 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009122 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009123 bool Changed = false;
9124
9125 // memmove/cpy/set of zero bytes is a noop.
9126 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9127 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9128
Chris Lattner35b9e482004-10-12 04:52:52 +00009129 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009130 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009131 // Replace the instruction with just byte operations. We would
9132 // transform other cases to loads/stores, but we don't know if
9133 // alignment is sufficient.
9134 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009135 }
9136
Chris Lattner35b9e482004-10-12 04:52:52 +00009137 // If we have a memmove and the source operation is a constant global,
9138 // then the source and dest pointers can't alias, so we can change this
9139 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009140 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009141 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9142 if (GVSrc->isConstant()) {
9143 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009144 Intrinsic::ID MemCpyID;
9145 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9146 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009147 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009148 MemCpyID = Intrinsic::memcpy_i64;
9149 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009150 Changed = true;
9151 }
Chris Lattner95a959d2006-03-06 20:18:44 +00009152 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009153
Chris Lattner95a959d2006-03-06 20:18:44 +00009154 // If we can determine a pointer alignment that is bigger than currently
9155 // set, update the alignment.
9156 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009157 if (Instruction *I = SimplifyMemTransfer(MI))
9158 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009159 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9160 if (Instruction *I = SimplifyMemSet(MSI))
9161 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009162 }
9163
Chris Lattner8b0ea312006-01-13 20:11:04 +00009164 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009165 } else {
9166 switch (II->getIntrinsicID()) {
9167 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009168 case Intrinsic::ppc_altivec_lvx:
9169 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009170 case Intrinsic::x86_sse_loadu_ps:
9171 case Intrinsic::x86_sse2_loadu_pd:
9172 case Intrinsic::x86_sse2_loadu_dq:
9173 // Turn PPC lvx -> load if the pointer is known aligned.
9174 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009175 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009176 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9177 PointerType::getUnqual(II->getType()),
9178 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009179 return new LoadInst(Ptr);
9180 }
9181 break;
9182 case Intrinsic::ppc_altivec_stvx:
9183 case Intrinsic::ppc_altivec_stvxl:
9184 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009185 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009186 const Type *OpPtrTy =
9187 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009188 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009189 return new StoreInst(II->getOperand(1), Ptr);
9190 }
9191 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009192 case Intrinsic::x86_sse_storeu_ps:
9193 case Intrinsic::x86_sse2_storeu_pd:
9194 case Intrinsic::x86_sse2_storeu_dq:
9195 case Intrinsic::x86_sse2_storel_dq:
9196 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009197 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009198 const Type *OpPtrTy =
9199 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009200 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009201 return new StoreInst(II->getOperand(2), Ptr);
9202 }
9203 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009204
9205 case Intrinsic::x86_sse_cvttss2si: {
9206 // These intrinsics only demands the 0th element of its input vector. If
9207 // we can simplify the input based on that, do so now.
9208 uint64_t UndefElts;
9209 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9210 UndefElts)) {
9211 II->setOperand(1, V);
9212 return II;
9213 }
9214 break;
9215 }
9216
Chris Lattnere2ed0572006-04-06 19:19:17 +00009217 case Intrinsic::ppc_altivec_vperm:
9218 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009219 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009220 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9221
9222 // Check that all of the elements are integer constants or undefs.
9223 bool AllEltsOk = true;
9224 for (unsigned i = 0; i != 16; ++i) {
9225 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9226 !isa<UndefValue>(Mask->getOperand(i))) {
9227 AllEltsOk = false;
9228 break;
9229 }
9230 }
9231
9232 if (AllEltsOk) {
9233 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009234 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9235 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009236 Value *Result = UndefValue::get(Op0->getType());
9237
9238 // Only extract each element once.
9239 Value *ExtractedElts[32];
9240 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9241
9242 for (unsigned i = 0; i != 16; ++i) {
9243 if (isa<UndefValue>(Mask->getOperand(i)))
9244 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009245 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009246 Idx &= 31; // Match the hardware behavior.
9247
9248 if (ExtractedElts[Idx] == 0) {
9249 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009250 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009251 InsertNewInstBefore(Elt, CI);
9252 ExtractedElts[Idx] = Elt;
9253 }
9254
9255 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009256 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9257 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009258 InsertNewInstBefore(cast<Instruction>(Result), CI);
9259 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009260 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009261 }
9262 }
9263 break;
9264
Chris Lattnera728ddc2006-01-13 21:28:09 +00009265 case Intrinsic::stackrestore: {
9266 // If the save is right next to the restore, remove the restore. This can
9267 // happen when variable allocas are DCE'd.
9268 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9269 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9270 BasicBlock::iterator BI = SS;
9271 if (&*++BI == II)
9272 return EraseInstFromFunction(CI);
9273 }
9274 }
9275
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009276 // Scan down this block to see if there is another stack restore in the
9277 // same block without an intervening call/alloca.
9278 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009279 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009280 bool CannotRemove = false;
9281 for (++BI; &*BI != TI; ++BI) {
9282 if (isa<AllocaInst>(BI)) {
9283 CannotRemove = true;
9284 break;
9285 }
9286 if (isa<CallInst>(BI)) {
9287 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009288 CannotRemove = true;
9289 break;
9290 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009291 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009292 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009293 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009294 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009295
9296 // If the stack restore is in a return/unwind block and if there are no
9297 // allocas or calls between the restore and the return, nuke the restore.
9298 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9299 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009300 break;
9301 }
9302 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009303 }
9304
Chris Lattner8b0ea312006-01-13 20:11:04 +00009305 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009306}
9307
9308// InvokeInst simplification
9309//
9310Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009311 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009312}
9313
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009314/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9315/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009316static bool isSafeToEliminateVarargsCast(const CallSite CS,
9317 const CastInst * const CI,
9318 const TargetData * const TD,
9319 const int ix) {
9320 if (!CI->isLosslessCast())
9321 return false;
9322
9323 // The size of ByVal arguments is derived from the type, so we
9324 // can't change to a type with a different size. If the size were
9325 // passed explicitly we could avoid this check.
9326 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9327 return true;
9328
9329 const Type* SrcTy =
9330 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9331 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9332 if (!SrcTy->isSized() || !DstTy->isSized())
9333 return false;
9334 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9335 return false;
9336 return true;
9337}
9338
Chris Lattnera44d8a22003-10-07 22:32:43 +00009339// visitCallSite - Improvements for call and invoke instructions.
9340//
9341Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009342 bool Changed = false;
9343
9344 // If the callee is a constexpr cast of a function, attempt to move the cast
9345 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009346 if (transformConstExprCastCall(CS)) return 0;
9347
Chris Lattner6c266db2003-10-07 22:54:13 +00009348 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009349
Chris Lattner08b22ec2005-05-13 07:09:09 +00009350 if (Function *CalleeF = dyn_cast<Function>(Callee))
9351 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9352 Instruction *OldCall = CS.getInstruction();
9353 // If the call and callee calling conventions don't match, this call must
9354 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009355 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009356 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9357 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009358 if (!OldCall->use_empty())
9359 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9360 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9361 return EraseInstFromFunction(*OldCall);
9362 return 0;
9363 }
9364
Chris Lattner17be6352004-10-18 02:59:09 +00009365 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9366 // This instruction is not reachable, just remove it. We insert a store to
9367 // undef so that we know that this code is not reachable, despite the fact
9368 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009369 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009370 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009371 CS.getInstruction());
9372
9373 if (!CS.getInstruction()->use_empty())
9374 CS.getInstruction()->
9375 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9376
9377 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9378 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009379 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9380 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009381 }
Chris Lattner17be6352004-10-18 02:59:09 +00009382 return EraseInstFromFunction(*CS.getInstruction());
9383 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009384
Duncan Sandscdb6d922007-09-17 10:26:40 +00009385 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9386 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9387 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9388 return transformCallThroughTrampoline(CS);
9389
Chris Lattner6c266db2003-10-07 22:54:13 +00009390 const PointerType *PTy = cast<PointerType>(Callee->getType());
9391 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9392 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009393 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009394 // See if we can optimize any arguments passed through the varargs area of
9395 // the call.
9396 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009397 E = CS.arg_end(); I != E; ++I, ++ix) {
9398 CastInst *CI = dyn_cast<CastInst>(*I);
9399 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9400 *I = CI->getOperand(0);
9401 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009402 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009403 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009404 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009405
Duncan Sandsf0c33542007-12-19 21:13:37 +00009406 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009407 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009408 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009409 Changed = true;
9410 }
9411
Chris Lattner6c266db2003-10-07 22:54:13 +00009412 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009413}
9414
Chris Lattner9fe38862003-06-19 17:00:31 +00009415// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9416// attempt to move the cast to the arguments of the call/invoke.
9417//
9418bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9419 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9420 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009421 if (CE->getOpcode() != Instruction::BitCast ||
9422 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009423 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009424 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009425 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009426 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009427
9428 // Okay, this is a cast from a function to a different type. Unless doing so
9429 // would cause a type conversion of one of our arguments, change this call to
9430 // be a direct call with arguments casted to the appropriate types.
9431 //
9432 const FunctionType *FT = Callee->getFunctionType();
9433 const Type *OldRetTy = Caller->getType();
9434
Devang Patel75e6f022008-03-11 18:04:06 +00009435 if (isa<StructType>(FT->getReturnType()))
9436 return false; // TODO: Handle multiple return values.
9437
Chris Lattnerf78616b2004-01-14 06:06:08 +00009438 // Check to see if we are changing the return type...
9439 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009440 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009441 // Conversion is ok if changing from pointer to int of same size.
9442 !(isa<PointerType>(FT->getReturnType()) &&
9443 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009444 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009445
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009446 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009447 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009448 FT->getReturnType() != Type::VoidTy &&
9449 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009450 return false; // Cannot transform this return value.
9451
Chris Lattner58d74912008-03-12 17:45:29 +00009452 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9453 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009454 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9455 return false; // Attribute not compatible with transformed value.
9456 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009457
Chris Lattnerf78616b2004-01-14 06:06:08 +00009458 // If the callsite is an invoke instruction, and the return value is used by
9459 // a PHI node in a successor, we cannot change the return type of the call
9460 // because there is no place to put the cast instruction (without breaking
9461 // the critical edge). Bail out in this case.
9462 if (!Caller->use_empty())
9463 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9464 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9465 UI != E; ++UI)
9466 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9467 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009468 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009469 return false;
9470 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009471
9472 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9473 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009474
Chris Lattner9fe38862003-06-19 17:00:31 +00009475 CallSite::arg_iterator AI = CS.arg_begin();
9476 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9477 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009478 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009479
9480 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009481 return false; // Cannot transform this parameter value.
9482
Chris Lattner58d74912008-03-12 17:45:29 +00009483 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9484 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009485
Reid Spencer3da59db2006-11-27 01:05:10 +00009486 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009487 // Some conversions are safe even if we do not have a body.
9488 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009489 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009490 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009491 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009492 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9493 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009494 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009495 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009496 }
9497
9498 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009499 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009500 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009501
Chris Lattner58d74912008-03-12 17:45:29 +00009502 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9503 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009504 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009505 // won't be dropping them. Check that these extra arguments have attributes
9506 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009507 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9508 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009509 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009510 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009511 if (PAttrs & ParamAttr::VarArgsIncompatible)
9512 return false;
9513 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009514
Chris Lattner9fe38862003-06-19 17:00:31 +00009515 // Okay, we decided that this is a safe thing to do: go ahead and start
9516 // inserting cast instructions as necessary...
9517 std::vector<Value*> Args;
9518 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009519 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009520 attrVec.reserve(NumCommonArgs);
9521
9522 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009523 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009524
9525 // If the return value is not being used, the type may not be compatible
9526 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009527 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009528
9529 // Add the new return attributes.
9530 if (RAttrs)
9531 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009532
9533 AI = CS.arg_begin();
9534 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9535 const Type *ParamTy = FT->getParamType(i);
9536 if ((*AI)->getType() == ParamTy) {
9537 Args.push_back(*AI);
9538 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009539 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009540 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009541 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009542 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009543 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009544
9545 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009546 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009547 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009548 }
9549
9550 // If the function takes more arguments than the call was taking, add them
9551 // now...
9552 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9553 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9554
9555 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009556 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009557 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009558 cerr << "WARNING: While resolving call to function '"
9559 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009560 } else {
9561 // Add all of the arguments in their promoted form to the arg list...
9562 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9563 const Type *PTy = getPromotedType((*AI)->getType());
9564 if (PTy != (*AI)->getType()) {
9565 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009566 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9567 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009568 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009569 InsertNewInstBefore(Cast, *Caller);
9570 Args.push_back(Cast);
9571 } else {
9572 Args.push_back(*AI);
9573 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009574
Duncan Sandse1e520f2008-01-13 08:02:44 +00009575 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009576 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009577 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9578 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009579 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009580 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009581
9582 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009583 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009584
Chris Lattner58d74912008-03-12 17:45:29 +00009585 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009586
Chris Lattner9fe38862003-06-19 17:00:31 +00009587 Instruction *NC;
9588 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009589 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009590 Args.begin(), Args.end(),
9591 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009592 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009593 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009594 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009595 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9596 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009597 CallInst *CI = cast<CallInst>(Caller);
9598 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009599 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009600 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009601 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009602 }
9603
Chris Lattner6934a042007-02-11 01:23:03 +00009604 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009605 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009606 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009607 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009608 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009609 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009610 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009611
9612 // If this is an invoke instruction, we should insert it after the first
9613 // non-phi, instruction in the normal successor block.
9614 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9615 BasicBlock::iterator I = II->getNormalDest()->begin();
9616 while (isa<PHINode>(I)) ++I;
9617 InsertNewInstBefore(NC, *I);
9618 } else {
9619 // Otherwise, it's a call, just insert cast right after the call instr
9620 InsertNewInstBefore(NC, *Caller);
9621 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009622 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009623 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009624 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009625 }
9626 }
9627
9628 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9629 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009630 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009631 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009632 return true;
9633}
9634
Duncan Sandscdb6d922007-09-17 10:26:40 +00009635// transformCallThroughTrampoline - Turn a call to a function created by the
9636// init_trampoline intrinsic into a direct call to the underlying function.
9637//
9638Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9639 Value *Callee = CS.getCalledValue();
9640 const PointerType *PTy = cast<PointerType>(Callee->getType());
9641 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009642 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009643
9644 // If the call already has the 'nest' attribute somewhere then give up -
9645 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009646 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009647 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009648
9649 IntrinsicInst *Tramp =
9650 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9651
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009652 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009653 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9654 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9655
Chris Lattner58d74912008-03-12 17:45:29 +00009656 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9657 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009658 unsigned NestIdx = 1;
9659 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009660 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009661
9662 // Look for a parameter marked with the 'nest' attribute.
9663 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9664 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009665 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009666 // Record the parameter type and any other attributes.
9667 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009668 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009669 break;
9670 }
9671
9672 if (NestTy) {
9673 Instruction *Caller = CS.getInstruction();
9674 std::vector<Value*> NewArgs;
9675 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9676
Chris Lattner58d74912008-03-12 17:45:29 +00009677 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9678 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009679
Duncan Sandscdb6d922007-09-17 10:26:40 +00009680 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009681 // mean appending it. Likewise for attributes.
9682
9683 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009684 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9685 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009686
Duncan Sandscdb6d922007-09-17 10:26:40 +00009687 {
9688 unsigned Idx = 1;
9689 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9690 do {
9691 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009692 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009693 Value *NestVal = Tramp->getOperand(3);
9694 if (NestVal->getType() != NestTy)
9695 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9696 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009697 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009698 }
9699
9700 if (I == E)
9701 break;
9702
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009703 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009704 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009705 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009706 NewAttrs.push_back
9707 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009708
9709 ++Idx, ++I;
9710 } while (1);
9711 }
9712
9713 // The trampoline may have been bitcast to a bogus type (FTy).
9714 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009715 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009716
Duncan Sandscdb6d922007-09-17 10:26:40 +00009717 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009718 NewTypes.reserve(FTy->getNumParams()+1);
9719
Duncan Sandscdb6d922007-09-17 10:26:40 +00009720 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009721 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009722 {
9723 unsigned Idx = 1;
9724 FunctionType::param_iterator I = FTy->param_begin(),
9725 E = FTy->param_end();
9726
9727 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009728 if (Idx == NestIdx)
9729 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009730 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009731
9732 if (I == E)
9733 break;
9734
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009735 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009736 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009737
9738 ++Idx, ++I;
9739 } while (1);
9740 }
9741
9742 // Replace the trampoline call with a direct call. Let the generic
9743 // code sort out any function type mismatches.
9744 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009745 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009746 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9747 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009748 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009749
9750 Instruction *NewCaller;
9751 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009752 NewCaller = InvokeInst::Create(NewCallee,
9753 II->getNormalDest(), II->getUnwindDest(),
9754 NewArgs.begin(), NewArgs.end(),
9755 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009756 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009757 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009758 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009759 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9760 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009761 if (cast<CallInst>(Caller)->isTailCall())
9762 cast<CallInst>(NewCaller)->setTailCall();
9763 cast<CallInst>(NewCaller)->
9764 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009765 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009766 }
9767 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9768 Caller->replaceAllUsesWith(NewCaller);
9769 Caller->eraseFromParent();
9770 RemoveFromWorkList(Caller);
9771 return 0;
9772 }
9773 }
9774
9775 // Replace the trampoline call with a direct call. Since there is no 'nest'
9776 // parameter, there is no need to adjust the argument list. Let the generic
9777 // code sort out any function type mismatches.
9778 Constant *NewCallee =
9779 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9780 CS.setCalledFunction(NewCallee);
9781 return CS.getInstruction();
9782}
9783
Chris Lattner7da52b22006-11-01 04:51:18 +00009784/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9785/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9786/// and a single binop.
9787Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9788 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009789 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9790 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009791 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009792 Value *LHSVal = FirstInst->getOperand(0);
9793 Value *RHSVal = FirstInst->getOperand(1);
9794
9795 const Type *LHSType = LHSVal->getType();
9796 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009797
9798 // Scan to see if all operands are the same opcode, all have one use, and all
9799 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009800 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009801 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009802 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009803 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009804 // types or GEP's with different index types.
9805 I->getOperand(0)->getType() != LHSType ||
9806 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009807 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009808
9809 // If they are CmpInst instructions, check their predicates
9810 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9811 if (cast<CmpInst>(I)->getPredicate() !=
9812 cast<CmpInst>(FirstInst)->getPredicate())
9813 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009814
9815 // Keep track of which operand needs a phi node.
9816 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9817 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009818 }
9819
Chris Lattner53738a42006-11-08 19:42:28 +00009820 // Otherwise, this is safe to transform, determine if it is profitable.
9821
9822 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9823 // Indexes are often folded into load/store instructions, so we don't want to
9824 // hide them behind a phi.
9825 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9826 return 0;
9827
Chris Lattner7da52b22006-11-01 04:51:18 +00009828 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009829 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009830 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009831 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009832 NewLHS = PHINode::Create(LHSType,
9833 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009834 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9835 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009836 InsertNewInstBefore(NewLHS, PN);
9837 LHSVal = NewLHS;
9838 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009839
9840 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009841 NewRHS = PHINode::Create(RHSType,
9842 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009843 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9844 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009845 InsertNewInstBefore(NewRHS, PN);
9846 RHSVal = NewRHS;
9847 }
9848
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009849 // Add all operands to the new PHIs.
9850 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9851 if (NewLHS) {
9852 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9853 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9854 }
9855 if (NewRHS) {
9856 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9857 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9858 }
9859 }
9860
Chris Lattner7da52b22006-11-01 04:51:18 +00009861 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009862 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009863 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009864 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009865 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009866 else {
9867 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009868 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009869 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009870}
9871
Chris Lattner76c73142006-11-01 07:13:54 +00009872/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9873/// of the block that defines it. This means that it must be obvious the value
9874/// of the load is not changed from the point of the load to the end of the
9875/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009876///
9877/// Finally, it is safe, but not profitable, to sink a load targetting a
9878/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9879/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009880static bool isSafeToSinkLoad(LoadInst *L) {
9881 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9882
9883 for (++BBI; BBI != E; ++BBI)
9884 if (BBI->mayWriteToMemory())
9885 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009886
9887 // Check for non-address taken alloca. If not address-taken already, it isn't
9888 // profitable to do this xform.
9889 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9890 bool isAddressTaken = false;
9891 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9892 UI != E; ++UI) {
9893 if (isa<LoadInst>(UI)) continue;
9894 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9895 // If storing TO the alloca, then the address isn't taken.
9896 if (SI->getOperand(1) == AI) continue;
9897 }
9898 isAddressTaken = true;
9899 break;
9900 }
9901
9902 if (!isAddressTaken)
9903 return false;
9904 }
9905
Chris Lattner76c73142006-11-01 07:13:54 +00009906 return true;
9907}
9908
Chris Lattner9fe38862003-06-19 17:00:31 +00009909
Chris Lattnerbac32862004-11-14 19:13:23 +00009910// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9911// operator and they all are only used by the PHI, PHI together their
9912// inputs, and do the operation once, to the result of the PHI.
9913Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9914 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9915
9916 // Scan the instruction, looking for input operations that can be folded away.
9917 // If all input operands to the phi are the same instruction (e.g. a cast from
9918 // the same type or "+42") we can pull the operation through the PHI, reducing
9919 // code size and simplifying code.
9920 Constant *ConstantOp = 0;
9921 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009922 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009923 if (isa<CastInst>(FirstInst)) {
9924 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009925 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009926 // Can fold binop, compare or shift here if the RHS is a constant,
9927 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009928 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009929 if (ConstantOp == 0)
9930 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009931 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9932 isVolatile = LI->isVolatile();
9933 // We can't sink the load if the loaded value could be modified between the
9934 // load and the PHI.
9935 if (LI->getParent() != PN.getIncomingBlock(0) ||
9936 !isSafeToSinkLoad(LI))
9937 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009938 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009939 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009940 return FoldPHIArgBinOpIntoPHI(PN);
9941 // Can't handle general GEPs yet.
9942 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009943 } else {
9944 return 0; // Cannot fold this operation.
9945 }
9946
9947 // Check to see if all arguments are the same operation.
9948 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9949 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9950 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009951 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009952 return 0;
9953 if (CastSrcTy) {
9954 if (I->getOperand(0)->getType() != CastSrcTy)
9955 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009956 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009957 // We can't sink the load if the loaded value could be modified between
9958 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009959 if (LI->isVolatile() != isVolatile ||
9960 LI->getParent() != PN.getIncomingBlock(i) ||
9961 !isSafeToSinkLoad(LI))
9962 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009963
9964 // If the PHI is volatile and its block has multiple successors, sinking
9965 // it would remove a load of the volatile value from the path through the
9966 // other successor.
9967 if (isVolatile &&
9968 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9969 return 0;
9970
9971
Chris Lattnerbac32862004-11-14 19:13:23 +00009972 } else if (I->getOperand(1) != ConstantOp) {
9973 return 0;
9974 }
9975 }
9976
9977 // Okay, they are all the same operation. Create a new PHI node of the
9978 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009979 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9980 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009981 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009982
9983 Value *InVal = FirstInst->getOperand(0);
9984 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009985
9986 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009987 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9988 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9989 if (NewInVal != InVal)
9990 InVal = 0;
9991 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9992 }
9993
9994 Value *PhiVal;
9995 if (InVal) {
9996 // The new PHI unions all of the same values together. This is really
9997 // common, so we handle it intelligently here for compile-time speed.
9998 PhiVal = InVal;
9999 delete NewPN;
10000 } else {
10001 InsertNewInstBefore(NewPN, PN);
10002 PhiVal = NewPN;
10003 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010004
Chris Lattnerbac32862004-11-14 19:13:23 +000010005 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010006 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010007 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010008 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010009 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010010 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010011 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010012 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010013 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10014
10015 // If this was a volatile load that we are merging, make sure to loop through
10016 // and mark all the input loads as non-volatile. If we don't do this, we will
10017 // insert a new volatile load and the old ones will not be deletable.
10018 if (isVolatile)
10019 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10020 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10021
10022 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010023}
Chris Lattnera1be5662002-05-02 17:06:02 +000010024
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010025/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10026/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010027static bool DeadPHICycle(PHINode *PN,
10028 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010029 if (PN->use_empty()) return true;
10030 if (!PN->hasOneUse()) return false;
10031
10032 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010033 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010034 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010035
10036 // Don't scan crazily complex things.
10037 if (PotentiallyDeadPHIs.size() == 16)
10038 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010039
10040 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10041 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010042
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010043 return false;
10044}
10045
Chris Lattnercf5008a2007-11-06 21:52:06 +000010046/// PHIsEqualValue - Return true if this phi node is always equal to
10047/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10048/// z = some value; x = phi (y, z); y = phi (x, z)
10049static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10050 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10051 // See if we already saw this PHI node.
10052 if (!ValueEqualPHIs.insert(PN))
10053 return true;
10054
10055 // Don't scan crazily complex things.
10056 if (ValueEqualPHIs.size() == 16)
10057 return false;
10058
10059 // Scan the operands to see if they are either phi nodes or are equal to
10060 // the value.
10061 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10062 Value *Op = PN->getIncomingValue(i);
10063 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10064 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10065 return false;
10066 } else if (Op != NonPhiInVal)
10067 return false;
10068 }
10069
10070 return true;
10071}
10072
10073
Chris Lattner473945d2002-05-06 18:06:38 +000010074// PHINode simplification
10075//
Chris Lattner7e708292002-06-25 16:13:24 +000010076Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010077 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010078 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010079
Owen Anderson7e057142006-07-10 22:03:18 +000010080 if (Value *V = PN.hasConstantValue())
10081 return ReplaceInstUsesWith(PN, V);
10082
Owen Anderson7e057142006-07-10 22:03:18 +000010083 // If all PHI operands are the same operation, pull them through the PHI,
10084 // reducing code size.
10085 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10086 PN.getIncomingValue(0)->hasOneUse())
10087 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10088 return Result;
10089
10090 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10091 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10092 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010093 if (PN.hasOneUse()) {
10094 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10095 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010096 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010097 PotentiallyDeadPHIs.insert(&PN);
10098 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10099 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10100 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010101
10102 // If this phi has a single use, and if that use just computes a value for
10103 // the next iteration of a loop, delete the phi. This occurs with unused
10104 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10105 // common case here is good because the only other things that catch this
10106 // are induction variable analysis (sometimes) and ADCE, which is only run
10107 // late.
10108 if (PHIUser->hasOneUse() &&
10109 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10110 PHIUser->use_back() == &PN) {
10111 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10112 }
10113 }
Owen Anderson7e057142006-07-10 22:03:18 +000010114
Chris Lattnercf5008a2007-11-06 21:52:06 +000010115 // We sometimes end up with phi cycles that non-obviously end up being the
10116 // same value, for example:
10117 // z = some value; x = phi (y, z); y = phi (x, z)
10118 // where the phi nodes don't necessarily need to be in the same block. Do a
10119 // quick check to see if the PHI node only contains a single non-phi value, if
10120 // so, scan to see if the phi cycle is actually equal to that value.
10121 {
10122 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10123 // Scan for the first non-phi operand.
10124 while (InValNo != NumOperandVals &&
10125 isa<PHINode>(PN.getIncomingValue(InValNo)))
10126 ++InValNo;
10127
10128 if (InValNo != NumOperandVals) {
10129 Value *NonPhiInVal = PN.getOperand(InValNo);
10130
10131 // Scan the rest of the operands to see if there are any conflicts, if so
10132 // there is no need to recursively scan other phis.
10133 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10134 Value *OpVal = PN.getIncomingValue(InValNo);
10135 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10136 break;
10137 }
10138
10139 // If we scanned over all operands, then we have one unique value plus
10140 // phi values. Scan PHI nodes to see if they all merge in each other or
10141 // the value.
10142 if (InValNo == NumOperandVals) {
10143 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10144 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10145 return ReplaceInstUsesWith(PN, NonPhiInVal);
10146 }
10147 }
10148 }
Chris Lattner60921c92003-12-19 05:58:40 +000010149 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010150}
10151
Reid Spencer17212df2006-12-12 09:18:51 +000010152static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10153 Instruction *InsertPoint,
10154 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010155 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10156 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010157 // We must cast correctly to the pointer type. Ensure that we
10158 // sign extend the integer value if it is smaller as this is
10159 // used for address computation.
10160 Instruction::CastOps opcode =
10161 (VTySize < PtrSize ? Instruction::SExt :
10162 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10163 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010164}
10165
Chris Lattnera1be5662002-05-02 17:06:02 +000010166
Chris Lattner7e708292002-06-25 16:13:24 +000010167Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010168 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010169 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010170 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010171 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010172 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010173
Chris Lattnere87597f2004-10-16 18:11:37 +000010174 if (isa<UndefValue>(GEP.getOperand(0)))
10175 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10176
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010177 bool HasZeroPointerIndex = false;
10178 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10179 HasZeroPointerIndex = C->isNullValue();
10180
10181 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010182 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010183
Chris Lattner28977af2004-04-05 01:30:19 +000010184 // Eliminate unneeded casts for indices.
10185 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010186
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010187 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010188 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010189 if (isa<SequentialType>(*GTI)) {
10190 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010191 if (CI->getOpcode() == Instruction::ZExt ||
10192 CI->getOpcode() == Instruction::SExt) {
10193 const Type *SrcTy = CI->getOperand(0)->getType();
10194 // We can eliminate a cast from i32 to i64 iff the target
10195 // is a 32-bit pointer target.
10196 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10197 MadeChange = true;
10198 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010199 }
10200 }
10201 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010202 // If we are using a wider index than needed for this platform, shrink it
10203 // to what we need. If the incoming value needs a cast instruction,
10204 // insert it. This explicit cast can make subsequent optimizations more
10205 // obvious.
10206 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010207 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010208 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010209 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010210 MadeChange = true;
10211 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010212 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10213 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010214 GEP.setOperand(i, Op);
10215 MadeChange = true;
10216 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010217 }
Chris Lattner28977af2004-04-05 01:30:19 +000010218 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010219 }
Chris Lattner28977af2004-04-05 01:30:19 +000010220 if (MadeChange) return &GEP;
10221
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010222 // If this GEP instruction doesn't move the pointer, and if the input operand
10223 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10224 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010225 if (GEP.hasAllZeroIndices()) {
10226 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10227 // If the bitcast is of an allocation, and the allocation will be
10228 // converted to match the type of the cast, don't touch this.
10229 if (isa<AllocationInst>(BCI->getOperand(0))) {
10230 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010231 if (Instruction *I = visitBitCast(*BCI)) {
10232 if (I != BCI) {
10233 I->takeName(BCI);
10234 BCI->getParent()->getInstList().insert(BCI, I);
10235 ReplaceInstUsesWith(*BCI, I);
10236 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010237 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010238 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010239 }
10240 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10241 }
10242 }
10243
Chris Lattner90ac28c2002-08-02 19:29:35 +000010244 // Combine Indices - If the source pointer to this getelementptr instruction
10245 // is a getelementptr instruction, combine the indices of the two
10246 // getelementptr instructions into a single instruction.
10247 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010248 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010249 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010250 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010251
10252 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010253 // Note that if our source is a gep chain itself that we wait for that
10254 // chain to be resolved before we perform this transformation. This
10255 // avoids us creating a TON of code in some cases.
10256 //
10257 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10258 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10259 return 0; // Wait until our source is folded to completion.
10260
Chris Lattner72588fc2007-02-15 22:48:32 +000010261 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010262
10263 // Find out whether the last index in the source GEP is a sequential idx.
10264 bool EndsWithSequential = false;
10265 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10266 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010267 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010268
Chris Lattner90ac28c2002-08-02 19:29:35 +000010269 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010270 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010271 // Replace: gep (gep %P, long B), long A, ...
10272 // With: T = long A+B; gep %P, T, ...
10273 //
Chris Lattner620ce142004-05-07 22:09:22 +000010274 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010275 if (SO1 == Constant::getNullValue(SO1->getType())) {
10276 Sum = GO1;
10277 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10278 Sum = SO1;
10279 } else {
10280 // If they aren't the same type, convert both to an integer of the
10281 // target's pointer size.
10282 if (SO1->getType() != GO1->getType()) {
10283 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010284 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010285 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010286 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010287 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010288 unsigned PS = TD->getPointerSizeInBits();
10289 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010290 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010291 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010292
Duncan Sands514ab342007-11-01 20:53:16 +000010293 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010294 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010295 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010296 } else {
10297 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010298 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10299 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010300 }
10301 }
10302 }
Chris Lattner620ce142004-05-07 22:09:22 +000010303 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10304 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10305 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010306 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010307 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010308 }
Chris Lattner28977af2004-04-05 01:30:19 +000010309 }
Chris Lattner620ce142004-05-07 22:09:22 +000010310
10311 // Recycle the GEP we already have if possible.
10312 if (SrcGEPOperands.size() == 2) {
10313 GEP.setOperand(0, SrcGEPOperands[0]);
10314 GEP.setOperand(1, Sum);
10315 return &GEP;
10316 } else {
10317 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10318 SrcGEPOperands.end()-1);
10319 Indices.push_back(Sum);
10320 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10321 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010322 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010323 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010324 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010325 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010326 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10327 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010328 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10329 }
10330
10331 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010332 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10333 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010334
Chris Lattner620ce142004-05-07 22:09:22 +000010335 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010336 // GEP of global variable. If all of the indices for this GEP are
10337 // constants, we can promote this to a constexpr instead of an instruction.
10338
10339 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010340 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010341 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10342 for (; I != E && isa<Constant>(*I); ++I)
10343 Indices.push_back(cast<Constant>(*I));
10344
10345 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010346 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10347 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010348
10349 // Replace all uses of the GEP with the new constexpr...
10350 return ReplaceInstUsesWith(GEP, CE);
10351 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010352 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010353 if (!isa<PointerType>(X->getType())) {
10354 // Not interesting. Source pointer must be a cast from pointer.
10355 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010356 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10357 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010358 //
10359 // This occurs when the program declares an array extern like "int X[];"
10360 //
10361 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10362 const PointerType *XTy = cast<PointerType>(X->getType());
10363 if (const ArrayType *XATy =
10364 dyn_cast<ArrayType>(XTy->getElementType()))
10365 if (const ArrayType *CATy =
10366 dyn_cast<ArrayType>(CPTy->getElementType()))
10367 if (CATy->getElementType() == XATy->getElementType()) {
10368 // At this point, we know that the cast source type is a pointer
10369 // to an array of the same type as the destination pointer
10370 // array. Because the array type is never stepped over (there
10371 // is a leading zero) we can fold the cast into this GEP.
10372 GEP.setOperand(0, X);
10373 return &GEP;
10374 }
10375 } else if (GEP.getNumOperands() == 2) {
10376 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010377 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10378 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010379 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10380 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10381 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010382 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10383 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010384 Value *Idx[2];
10385 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10386 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010387 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010388 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010389 // V and GEP are both pointer types --> BitCast
10390 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010391 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010392
10393 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010394 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010395 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010396 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010397
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010398 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010399 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010400 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010401
10402 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10403 // allow either a mul, shift, or constant here.
10404 Value *NewIdx = 0;
10405 ConstantInt *Scale = 0;
10406 if (ArrayEltSize == 1) {
10407 NewIdx = GEP.getOperand(1);
10408 Scale = ConstantInt::get(NewIdx->getType(), 1);
10409 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010410 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010411 Scale = CI;
10412 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10413 if (Inst->getOpcode() == Instruction::Shl &&
10414 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010415 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10416 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10417 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010418 NewIdx = Inst->getOperand(0);
10419 } else if (Inst->getOpcode() == Instruction::Mul &&
10420 isa<ConstantInt>(Inst->getOperand(1))) {
10421 Scale = cast<ConstantInt>(Inst->getOperand(1));
10422 NewIdx = Inst->getOperand(0);
10423 }
10424 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010425
Chris Lattner7835cdd2005-09-13 18:36:04 +000010426 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010427 // out, perform the transformation. Note, we don't know whether Scale is
10428 // signed or not. We'll use unsigned version of division/modulo
10429 // operation after making sure Scale doesn't have the sign bit set.
10430 if (Scale && Scale->getSExtValue() >= 0LL &&
10431 Scale->getZExtValue() % ArrayEltSize == 0) {
10432 Scale = ConstantInt::get(Scale->getType(),
10433 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010434 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010435 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010436 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010437 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010438 NewIdx = InsertNewInstBefore(Sc, GEP);
10439 }
10440
10441 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010442 Value *Idx[2];
10443 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10444 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010445 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010446 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010447 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10448 // The NewGEP must be pointer typed, so must the old one -> BitCast
10449 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010450 }
10451 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010452 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010453 }
10454
Chris Lattner8a2a3112001-12-14 16:52:21 +000010455 return 0;
10456}
10457
Chris Lattner0864acf2002-11-04 16:18:53 +000010458Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10459 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010460 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010461 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10462 const Type *NewTy =
10463 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010464 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010465
10466 // Create and insert the replacement instruction...
10467 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010468 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010469 else {
10470 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010471 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010472 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010473
10474 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010475
Chris Lattner0864acf2002-11-04 16:18:53 +000010476 // Scan to the end of the allocation instructions, to skip over a block of
10477 // allocas if possible...
10478 //
10479 BasicBlock::iterator It = New;
10480 while (isa<AllocationInst>(*It)) ++It;
10481
10482 // Now that I is pointing to the first non-allocation-inst in the block,
10483 // insert our getelementptr instruction...
10484 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010485 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010486 Value *Idx[2];
10487 Idx[0] = NullIdx;
10488 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010489 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10490 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010491
10492 // Now make everything use the getelementptr instead of the original
10493 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010494 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010495 } else if (isa<UndefValue>(AI.getArraySize())) {
10496 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010497 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010498 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010499
10500 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10501 // Note that we only do this for alloca's, because malloc should allocate and
10502 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010503 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010504 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010505 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10506
Chris Lattner0864acf2002-11-04 16:18:53 +000010507 return 0;
10508}
10509
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010510Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10511 Value *Op = FI.getOperand(0);
10512
Chris Lattner17be6352004-10-18 02:59:09 +000010513 // free undef -> unreachable.
10514 if (isa<UndefValue>(Op)) {
10515 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010516 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010517 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010518 return EraseInstFromFunction(FI);
10519 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010520
Chris Lattner6160e852004-02-28 04:57:37 +000010521 // If we have 'free null' delete the instruction. This can happen in stl code
10522 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010523 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010524 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010525
10526 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10527 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10528 FI.setOperand(0, CI->getOperand(0));
10529 return &FI;
10530 }
10531
10532 // Change free (gep X, 0,0,0,0) into free(X)
10533 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10534 if (GEPI->hasAllZeroIndices()) {
10535 AddToWorkList(GEPI);
10536 FI.setOperand(0, GEPI->getOperand(0));
10537 return &FI;
10538 }
10539 }
10540
10541 // Change free(malloc) into nothing, if the malloc has a single use.
10542 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10543 if (MI->hasOneUse()) {
10544 EraseInstFromFunction(FI);
10545 return EraseInstFromFunction(*MI);
10546 }
Chris Lattner6160e852004-02-28 04:57:37 +000010547
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010548 return 0;
10549}
10550
10551
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010552/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010553static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010554 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010555 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010556 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010557
Devang Patel99db6ad2007-10-18 19:52:32 +000010558 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10559 // Instead of loading constant c string, use corresponding integer value
10560 // directly if string length is small enough.
10561 const std::string &Str = CE->getOperand(0)->getStringValue();
10562 if (!Str.empty()) {
10563 unsigned len = Str.length();
10564 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10565 unsigned numBits = Ty->getPrimitiveSizeInBits();
10566 // Replace LI with immediate integer store.
10567 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010568 APInt StrVal(numBits, 0);
10569 APInt SingleChar(numBits, 0);
10570 if (TD->isLittleEndian()) {
10571 for (signed i = len-1; i >= 0; i--) {
10572 SingleChar = (uint64_t) Str[i];
10573 StrVal = (StrVal << 8) | SingleChar;
10574 }
10575 } else {
10576 for (unsigned i = 0; i < len; i++) {
10577 SingleChar = (uint64_t) Str[i];
10578 StrVal = (StrVal << 8) | SingleChar;
10579 }
10580 // Append NULL at the end.
10581 SingleChar = 0;
10582 StrVal = (StrVal << 8) | SingleChar;
10583 }
10584 Value *NL = ConstantInt::get(StrVal);
10585 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010586 }
10587 }
10588 }
10589
Chris Lattnerb89e0712004-07-13 01:49:43 +000010590 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010591 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010592 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010593
Reid Spencer42230162007-01-22 05:51:25 +000010594 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010595 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010596 // If the source is an array, the code below will not succeed. Check to
10597 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10598 // constants.
10599 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10600 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10601 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010602 Value *Idxs[2];
10603 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10604 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010605 SrcTy = cast<PointerType>(CastOp->getType());
10606 SrcPTy = SrcTy->getElementType();
10607 }
10608
Reid Spencer42230162007-01-22 05:51:25 +000010609 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010610 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010611 // Do not allow turning this into a load of an integer, which is then
10612 // casted to a pointer, this pessimizes pointer analysis a lot.
10613 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010614 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10615 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010616
Chris Lattnerf9527852005-01-31 04:50:46 +000010617 // Okay, we are casting from one integer or pointer type to another of
10618 // the same size. Instead of casting the pointer before the load, cast
10619 // the result of the loaded value.
10620 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10621 CI->getName(),
10622 LI.isVolatile()),LI);
10623 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010624 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010625 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010626 }
10627 }
10628 return 0;
10629}
10630
Chris Lattnerc10aced2004-09-19 18:43:46 +000010631/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010632/// from this value cannot trap. If it is not obviously safe to load from the
10633/// specified pointer, we do a quick local scan of the basic block containing
10634/// ScanFrom, to determine if the address is already accessed.
10635static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010636 // If it is an alloca it is always safe to load from.
10637 if (isa<AllocaInst>(V)) return true;
10638
Duncan Sands46318cd2007-09-19 10:25:38 +000010639 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010640 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010641 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010642 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010643
10644 // Otherwise, be a little bit agressive by scanning the local block where we
10645 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010646 // from/to. If so, the previous load or store would have already trapped,
10647 // so there is no harm doing an extra load (also, CSE will later eliminate
10648 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010649 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10650
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010651 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010652 --BBI;
10653
10654 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10655 if (LI->getOperand(0) == V) return true;
10656 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10657 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010658
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010659 }
Chris Lattner8a375202004-09-19 19:18:10 +000010660 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010661}
10662
Chris Lattner8d2e8882007-08-11 18:48:48 +000010663/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10664/// until we find the underlying object a pointer is referring to or something
10665/// we don't understand. Note that the returned pointer may be offset from the
10666/// input, because we ignore GEP indices.
10667static Value *GetUnderlyingObject(Value *Ptr) {
10668 while (1) {
10669 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10670 if (CE->getOpcode() == Instruction::BitCast ||
10671 CE->getOpcode() == Instruction::GetElementPtr)
10672 Ptr = CE->getOperand(0);
10673 else
10674 return Ptr;
10675 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10676 Ptr = BCI->getOperand(0);
10677 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10678 Ptr = GEP->getOperand(0);
10679 } else {
10680 return Ptr;
10681 }
10682 }
10683}
10684
Chris Lattner833b8a42003-06-26 05:06:25 +000010685Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10686 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010687
Dan Gohman9941f742007-07-20 16:34:21 +000010688 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010689 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10690 if (KnownAlign >
10691 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10692 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010693 LI.setAlignment(KnownAlign);
10694
Chris Lattner37366c12005-05-01 04:24:53 +000010695 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010696 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010697 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010698 return Res;
10699
10700 // None of the following transforms are legal for volatile loads.
10701 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010702
Chris Lattner62f254d2005-09-12 22:00:15 +000010703 if (&LI.getParent()->front() != &LI) {
10704 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010705 // If the instruction immediately before this is a store to the same
10706 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010707 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10708 if (SI->getOperand(1) == LI.getOperand(0))
10709 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010710 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10711 if (LIB->getOperand(0) == LI.getOperand(0))
10712 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010713 }
Chris Lattner37366c12005-05-01 04:24:53 +000010714
Christopher Lambb15147e2007-12-29 07:56:53 +000010715 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10716 const Value *GEPI0 = GEPI->getOperand(0);
10717 // TODO: Consider a target hook for valid address spaces for this xform.
10718 if (isa<ConstantPointerNull>(GEPI0) &&
10719 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010720 // Insert a new store to null instruction before the load to indicate
10721 // that this code is not reachable. We do this instead of inserting
10722 // an unreachable instruction directly because we cannot modify the
10723 // CFG.
10724 new StoreInst(UndefValue::get(LI.getType()),
10725 Constant::getNullValue(Op->getType()), &LI);
10726 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10727 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010728 }
Chris Lattner37366c12005-05-01 04:24:53 +000010729
Chris Lattnere87597f2004-10-16 18:11:37 +000010730 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010731 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010732 // TODO: Consider a target hook for valid address spaces for this xform.
10733 if (isa<UndefValue>(C) || (C->isNullValue() &&
10734 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010735 // Insert a new store to null instruction before the load to indicate that
10736 // this code is not reachable. We do this instead of inserting an
10737 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010738 new StoreInst(UndefValue::get(LI.getType()),
10739 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010740 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010741 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010742
Chris Lattnere87597f2004-10-16 18:11:37 +000010743 // Instcombine load (constant global) into the value loaded.
10744 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010745 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010746 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010747
Chris Lattnere87597f2004-10-16 18:11:37 +000010748 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010749 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010750 if (CE->getOpcode() == Instruction::GetElementPtr) {
10751 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010752 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010753 if (Constant *V =
10754 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010755 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010756 if (CE->getOperand(0)->isNullValue()) {
10757 // Insert a new store to null instruction before the load to indicate
10758 // that this code is not reachable. We do this instead of inserting
10759 // an unreachable instruction directly because we cannot modify the
10760 // CFG.
10761 new StoreInst(UndefValue::get(LI.getType()),
10762 Constant::getNullValue(Op->getType()), &LI);
10763 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10764 }
10765
Reid Spencer3da59db2006-11-27 01:05:10 +000010766 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010767 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010768 return Res;
10769 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010770 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010771 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010772
10773 // If this load comes from anywhere in a constant global, and if the global
10774 // is all undef or zero, we know what it loads.
10775 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10776 if (GV->isConstant() && GV->hasInitializer()) {
10777 if (GV->getInitializer()->isNullValue())
10778 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10779 else if (isa<UndefValue>(GV->getInitializer()))
10780 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10781 }
10782 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010783
Chris Lattner37366c12005-05-01 04:24:53 +000010784 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010785 // Change select and PHI nodes to select values instead of addresses: this
10786 // helps alias analysis out a lot, allows many others simplifications, and
10787 // exposes redundancy in the code.
10788 //
10789 // Note that we cannot do the transformation unless we know that the
10790 // introduced loads cannot trap! Something like this is valid as long as
10791 // the condition is always false: load (select bool %C, int* null, int* %G),
10792 // but it would not be valid if we transformed it to load from null
10793 // unconditionally.
10794 //
10795 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10796 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010797 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10798 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010799 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010800 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010801 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010802 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010803 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010804 }
10805
Chris Lattner684fe212004-09-23 15:46:00 +000010806 // load (select (cond, null, P)) -> load P
10807 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10808 if (C->isNullValue()) {
10809 LI.setOperand(0, SI->getOperand(2));
10810 return &LI;
10811 }
10812
10813 // load (select (cond, P, null)) -> load P
10814 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10815 if (C->isNullValue()) {
10816 LI.setOperand(0, SI->getOperand(1));
10817 return &LI;
10818 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010819 }
10820 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010821 return 0;
10822}
10823
Reid Spencer55af2b52007-01-19 21:20:31 +000010824/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010825/// when possible.
10826static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10827 User *CI = cast<User>(SI.getOperand(1));
10828 Value *CastOp = CI->getOperand(0);
10829
10830 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10831 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10832 const Type *SrcPTy = SrcTy->getElementType();
10833
Reid Spencer42230162007-01-22 05:51:25 +000010834 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010835 // If the source is an array, the code below will not succeed. Check to
10836 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10837 // constants.
10838 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10839 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10840 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010841 Value* Idxs[2];
10842 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10843 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010844 SrcTy = cast<PointerType>(CastOp->getType());
10845 SrcPTy = SrcTy->getElementType();
10846 }
10847
Reid Spencer67f827c2007-01-20 23:35:48 +000010848 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10849 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10850 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010851
10852 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010853 // the same size. Instead of casting the pointer before
10854 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010855 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010856 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010857 Instruction::CastOps opcode = Instruction::BitCast;
10858 const Type* CastSrcTy = SIOp0->getType();
10859 const Type* CastDstTy = SrcPTy;
10860 if (isa<PointerType>(CastDstTy)) {
10861 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010862 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010863 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010864 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010865 opcode = Instruction::PtrToInt;
10866 }
10867 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010868 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010869 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010870 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010871 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010872 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010873 return new StoreInst(NewCast, CastOp);
10874 }
10875 }
10876 }
10877 return 0;
10878}
10879
Chris Lattner2f503e62005-01-31 05:36:43 +000010880Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10881 Value *Val = SI.getOperand(0);
10882 Value *Ptr = SI.getOperand(1);
10883
10884 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010885 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010886 ++NumCombined;
10887 return 0;
10888 }
Chris Lattner836692d2007-01-15 06:51:56 +000010889
10890 // If the RHS is an alloca with a single use, zapify the store, making the
10891 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010892 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010893 if (isa<AllocaInst>(Ptr)) {
10894 EraseInstFromFunction(SI);
10895 ++NumCombined;
10896 return 0;
10897 }
10898
10899 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10900 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10901 GEP->getOperand(0)->hasOneUse()) {
10902 EraseInstFromFunction(SI);
10903 ++NumCombined;
10904 return 0;
10905 }
10906 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010907
Dan Gohman9941f742007-07-20 16:34:21 +000010908 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010909 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10910 if (KnownAlign >
10911 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10912 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010913 SI.setAlignment(KnownAlign);
10914
Chris Lattner9ca96412006-02-08 03:25:32 +000010915 // Do really simple DSE, to catch cases where there are several consequtive
10916 // stores to the same location, separated by a few arithmetic operations. This
10917 // situation often occurs with bitfield accesses.
10918 BasicBlock::iterator BBI = &SI;
10919 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10920 --ScanInsts) {
10921 --BBI;
10922
10923 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10924 // Prev store isn't volatile, and stores to the same location?
10925 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10926 ++NumDeadStore;
10927 ++BBI;
10928 EraseInstFromFunction(*PrevSI);
10929 continue;
10930 }
10931 break;
10932 }
10933
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010934 // If this is a load, we have to stop. However, if the loaded value is from
10935 // the pointer we're loading and is producing the pointer we're storing,
10936 // then *this* store is dead (X = load P; store X -> P).
10937 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010938 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010939 EraseInstFromFunction(SI);
10940 ++NumCombined;
10941 return 0;
10942 }
10943 // Otherwise, this is a load from some other location. Stores before it
10944 // may not be dead.
10945 break;
10946 }
10947
Chris Lattner9ca96412006-02-08 03:25:32 +000010948 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010949 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010950 break;
10951 }
10952
10953
10954 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010955
10956 // store X, null -> turns into 'unreachable' in SimplifyCFG
10957 if (isa<ConstantPointerNull>(Ptr)) {
10958 if (!isa<UndefValue>(Val)) {
10959 SI.setOperand(0, UndefValue::get(Val->getType()));
10960 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010961 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010962 ++NumCombined;
10963 }
10964 return 0; // Do not modify these!
10965 }
10966
10967 // store undef, Ptr -> noop
10968 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010969 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010970 ++NumCombined;
10971 return 0;
10972 }
10973
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010974 // If the pointer destination is a cast, see if we can fold the cast into the
10975 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010976 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010977 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10978 return Res;
10979 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010980 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010981 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10982 return Res;
10983
Chris Lattner408902b2005-09-12 23:23:25 +000010984
10985 // If this store is the last instruction in the basic block, and if the block
10986 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010987 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010988 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010989 if (BI->isUnconditional())
10990 if (SimplifyStoreAtEndOfBlock(SI))
10991 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010992
Chris Lattner2f503e62005-01-31 05:36:43 +000010993 return 0;
10994}
10995
Chris Lattner3284d1f2007-04-15 00:07:55 +000010996/// SimplifyStoreAtEndOfBlock - Turn things like:
10997/// if () { *P = v1; } else { *P = v2 }
10998/// into a phi node with a store in the successor.
10999///
Chris Lattner31755a02007-04-15 01:02:18 +000011000/// Simplify things like:
11001/// *P = v1; if () { *P = v2; }
11002/// into a phi node with a store in the successor.
11003///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011004bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11005 BasicBlock *StoreBB = SI.getParent();
11006
11007 // Check to see if the successor block has exactly two incoming edges. If
11008 // so, see if the other predecessor contains a store to the same location.
11009 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011010 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011011
11012 // Determine whether Dest has exactly two predecessors and, if so, compute
11013 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011014 pred_iterator PI = pred_begin(DestBB);
11015 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011016 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011017 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011018 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011019 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011020 return false;
11021
11022 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011023 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011024 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011025 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011026 }
Chris Lattner31755a02007-04-15 01:02:18 +000011027 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011028 return false;
11029
11030
Chris Lattner31755a02007-04-15 01:02:18 +000011031 // Verify that the other block ends in a branch and is not otherwise empty.
11032 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011033 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011034 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011035 return false;
11036
Chris Lattner31755a02007-04-15 01:02:18 +000011037 // If the other block ends in an unconditional branch, check for the 'if then
11038 // else' case. there is an instruction before the branch.
11039 StoreInst *OtherStore = 0;
11040 if (OtherBr->isUnconditional()) {
11041 // If this isn't a store, or isn't a store to the same location, bail out.
11042 --BBI;
11043 OtherStore = dyn_cast<StoreInst>(BBI);
11044 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11045 return false;
11046 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011047 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011048 // destinations is StoreBB, then we have the if/then case.
11049 if (OtherBr->getSuccessor(0) != StoreBB &&
11050 OtherBr->getSuccessor(1) != StoreBB)
11051 return false;
11052
11053 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011054 // if/then triangle. See if there is a store to the same ptr as SI that
11055 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011056 for (;; --BBI) {
11057 // Check to see if we find the matching store.
11058 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11059 if (OtherStore->getOperand(1) != SI.getOperand(1))
11060 return false;
11061 break;
11062 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011063 // If we find something that may be using the stored value, or if we run
11064 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011065 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11066 BBI == OtherBB->begin())
11067 return false;
11068 }
11069
11070 // In order to eliminate the store in OtherBr, we have to
11071 // make sure nothing reads the stored value in StoreBB.
11072 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11073 // FIXME: This should really be AA driven.
11074 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11075 return false;
11076 }
11077 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011078
Chris Lattner31755a02007-04-15 01:02:18 +000011079 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011080 Value *MergedVal = OtherStore->getOperand(0);
11081 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011082 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011083 PN->reserveOperandSpace(2);
11084 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011085 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11086 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011087 }
11088
11089 // Advance to a place where it is safe to insert the new store and
11090 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000011091 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011092 while (isa<PHINode>(BBI)) ++BBI;
11093 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11094 OtherStore->isVolatile()), *BBI);
11095
11096 // Nuke the old stores.
11097 EraseInstFromFunction(SI);
11098 EraseInstFromFunction(*OtherStore);
11099 ++NumCombined;
11100 return true;
11101}
11102
Chris Lattner2f503e62005-01-31 05:36:43 +000011103
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011104Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11105 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011106 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011107 BasicBlock *TrueDest;
11108 BasicBlock *FalseDest;
11109 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11110 !isa<Constant>(X)) {
11111 // Swap Destinations and condition...
11112 BI.setCondition(X);
11113 BI.setSuccessor(0, FalseDest);
11114 BI.setSuccessor(1, TrueDest);
11115 return &BI;
11116 }
11117
Reid Spencere4d87aa2006-12-23 06:05:41 +000011118 // Cannonicalize fcmp_one -> fcmp_oeq
11119 FCmpInst::Predicate FPred; Value *Y;
11120 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11121 TrueDest, FalseDest)))
11122 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11123 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11124 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011125 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011126 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11127 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011128 // Swap Destinations and condition...
11129 BI.setCondition(NewSCC);
11130 BI.setSuccessor(0, FalseDest);
11131 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011132 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011133 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011134 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011135 return &BI;
11136 }
11137
11138 // Cannonicalize icmp_ne -> icmp_eq
11139 ICmpInst::Predicate IPred;
11140 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11141 TrueDest, FalseDest)))
11142 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11143 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11144 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11145 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011146 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011147 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11148 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011149 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011150 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011151 BI.setSuccessor(0, FalseDest);
11152 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011153 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011154 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011155 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011156 return &BI;
11157 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011158
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011159 return 0;
11160}
Chris Lattner0864acf2002-11-04 16:18:53 +000011161
Chris Lattner46238a62004-07-03 00:26:11 +000011162Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11163 Value *Cond = SI.getCondition();
11164 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11165 if (I->getOpcode() == Instruction::Add)
11166 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11167 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11168 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011169 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011170 AddRHS));
11171 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011172 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011173 return &SI;
11174 }
11175 }
11176 return 0;
11177}
11178
Chris Lattner220b0cf2006-03-05 00:22:33 +000011179/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11180/// is to leave as a vector operation.
11181static bool CheapToScalarize(Value *V, bool isConstant) {
11182 if (isa<ConstantAggregateZero>(V))
11183 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011184 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011185 if (isConstant) return true;
11186 // If all elts are the same, we can extract.
11187 Constant *Op0 = C->getOperand(0);
11188 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11189 if (C->getOperand(i) != Op0)
11190 return false;
11191 return true;
11192 }
11193 Instruction *I = dyn_cast<Instruction>(V);
11194 if (!I) return false;
11195
11196 // Insert element gets simplified to the inserted element or is deleted if
11197 // this is constant idx extract element and its a constant idx insertelt.
11198 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11199 isa<ConstantInt>(I->getOperand(2)))
11200 return true;
11201 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11202 return true;
11203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11204 if (BO->hasOneUse() &&
11205 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11206 CheapToScalarize(BO->getOperand(1), isConstant)))
11207 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011208 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11209 if (CI->hasOneUse() &&
11210 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11211 CheapToScalarize(CI->getOperand(1), isConstant)))
11212 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011213
11214 return false;
11215}
11216
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011217/// Read and decode a shufflevector mask.
11218///
11219/// It turns undef elements into values that are larger than the number of
11220/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011221static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11222 unsigned NElts = SVI->getType()->getNumElements();
11223 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11224 return std::vector<unsigned>(NElts, 0);
11225 if (isa<UndefValue>(SVI->getOperand(2)))
11226 return std::vector<unsigned>(NElts, 2*NElts);
11227
11228 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011229 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011230 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11231 if (isa<UndefValue>(CP->getOperand(i)))
11232 Result.push_back(NElts*2); // undef -> 8
11233 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011234 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011235 return Result;
11236}
11237
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011238/// FindScalarElement - Given a vector and an element number, see if the scalar
11239/// value is already around as a register, for example if it were inserted then
11240/// extracted from the vector.
11241static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011242 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11243 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011244 unsigned Width = PTy->getNumElements();
11245 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011246 return UndefValue::get(PTy->getElementType());
11247
11248 if (isa<UndefValue>(V))
11249 return UndefValue::get(PTy->getElementType());
11250 else if (isa<ConstantAggregateZero>(V))
11251 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011252 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011253 return CP->getOperand(EltNo);
11254 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11255 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011256 if (!isa<ConstantInt>(III->getOperand(2)))
11257 return 0;
11258 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011259
11260 // If this is an insert to the element we are looking for, return the
11261 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011262 if (EltNo == IIElt)
11263 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011264
11265 // Otherwise, the insertelement doesn't modify the value, recurse on its
11266 // vector input.
11267 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011268 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011269 unsigned InEl = getShuffleMask(SVI)[EltNo];
11270 if (InEl < Width)
11271 return FindScalarElement(SVI->getOperand(0), InEl);
11272 else if (InEl < Width*2)
11273 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11274 else
11275 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011276 }
11277
11278 // Otherwise, we don't know.
11279 return 0;
11280}
11281
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011282Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011283
Dan Gohman07a96762007-07-16 14:29:03 +000011284 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011285 if (isa<UndefValue>(EI.getOperand(0)))
11286 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11287
Dan Gohman07a96762007-07-16 14:29:03 +000011288 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011289 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11290 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11291
Reid Spencer9d6565a2007-02-15 02:26:10 +000011292 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011293 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011294 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011295 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011296 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011297 if (C->getOperand(i) != op0) {
11298 op0 = 0;
11299 break;
11300 }
11301 if (op0)
11302 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011303 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011304
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011305 // If extracting a specified index from the vector, see if we can recursively
11306 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011307 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011308 unsigned IndexVal = IdxC->getZExtValue();
11309 unsigned VectorWidth =
11310 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11311
11312 // If this is extracting an invalid index, turn this into undef, to avoid
11313 // crashing the code below.
11314 if (IndexVal >= VectorWidth)
11315 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11316
Chris Lattner867b99f2006-10-05 06:55:50 +000011317 // This instruction only demands the single element from the input vector.
11318 // If the input vector has a single use, simplify it based on this use
11319 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011320 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011321 uint64_t UndefElts;
11322 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011323 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011324 UndefElts)) {
11325 EI.setOperand(0, V);
11326 return &EI;
11327 }
11328 }
11329
Reid Spencerb83eb642006-10-20 07:07:24 +000011330 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011331 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011332
11333 // If the this extractelement is directly using a bitcast from a vector of
11334 // the same number of elements, see if we can find the source element from
11335 // it. In this case, we will end up needing to bitcast the scalars.
11336 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11337 if (const VectorType *VT =
11338 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11339 if (VT->getNumElements() == VectorWidth)
11340 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11341 return new BitCastInst(Elt, EI.getType());
11342 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011343 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011344
Chris Lattner73fa49d2006-05-25 22:53:38 +000011345 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011346 if (I->hasOneUse()) {
11347 // Push extractelement into predecessor operation if legal and
11348 // profitable to do so
11349 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011350 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11351 if (CheapToScalarize(BO, isConstantElt)) {
11352 ExtractElementInst *newEI0 =
11353 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11354 EI.getName()+".lhs");
11355 ExtractElementInst *newEI1 =
11356 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11357 EI.getName()+".rhs");
11358 InsertNewInstBefore(newEI0, EI);
11359 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011360 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011361 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011362 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011363 unsigned AS =
11364 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011365 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11366 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011367 GetElementPtrInst *GEP =
11368 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011369 InsertNewInstBefore(GEP, EI);
11370 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011371 }
11372 }
11373 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11374 // Extracting the inserted element?
11375 if (IE->getOperand(2) == EI.getOperand(1))
11376 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11377 // If the inserted and extracted elements are constants, they must not
11378 // be the same value, extract from the pre-inserted value instead.
11379 if (isa<Constant>(IE->getOperand(2)) &&
11380 isa<Constant>(EI.getOperand(1))) {
11381 AddUsesToWorkList(EI);
11382 EI.setOperand(0, IE->getOperand(0));
11383 return &EI;
11384 }
11385 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11386 // If this is extracting an element from a shufflevector, figure out where
11387 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011388 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11389 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011390 Value *Src;
11391 if (SrcIdx < SVI->getType()->getNumElements())
11392 Src = SVI->getOperand(0);
11393 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11394 SrcIdx -= SVI->getType()->getNumElements();
11395 Src = SVI->getOperand(1);
11396 } else {
11397 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011398 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011399 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011400 }
11401 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011402 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011403 return 0;
11404}
11405
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011406/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11407/// elements from either LHS or RHS, return the shuffle mask and true.
11408/// Otherwise, return false.
11409static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11410 std::vector<Constant*> &Mask) {
11411 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11412 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011413 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011414
11415 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011416 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011417 return true;
11418 } else if (V == LHS) {
11419 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011420 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011421 return true;
11422 } else if (V == RHS) {
11423 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011424 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011425 return true;
11426 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11427 // If this is an insert of an extract from some other vector, include it.
11428 Value *VecOp = IEI->getOperand(0);
11429 Value *ScalarOp = IEI->getOperand(1);
11430 Value *IdxOp = IEI->getOperand(2);
11431
Chris Lattnerd929f062006-04-27 21:14:21 +000011432 if (!isa<ConstantInt>(IdxOp))
11433 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011434 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011435
11436 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11437 // Okay, we can handle this if the vector we are insertinting into is
11438 // transitively ok.
11439 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11440 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011441 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011442 return true;
11443 }
11444 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11445 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011446 EI->getOperand(0)->getType() == V->getType()) {
11447 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011448 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011449
11450 // This must be extracting from either LHS or RHS.
11451 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11452 // Okay, we can handle this if the vector we are insertinting into is
11453 // transitively ok.
11454 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11455 // If so, update the mask to reflect the inserted value.
11456 if (EI->getOperand(0) == LHS) {
11457 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011458 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011459 } else {
11460 assert(EI->getOperand(0) == RHS);
11461 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011462 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011463
11464 }
11465 return true;
11466 }
11467 }
11468 }
11469 }
11470 }
11471 // TODO: Handle shufflevector here!
11472
11473 return false;
11474}
11475
11476/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11477/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11478/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011479static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011480 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011481 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011482 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011483 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011484 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011485
11486 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011487 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011488 return V;
11489 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011490 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011491 return V;
11492 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11493 // If this is an insert of an extract from some other vector, include it.
11494 Value *VecOp = IEI->getOperand(0);
11495 Value *ScalarOp = IEI->getOperand(1);
11496 Value *IdxOp = IEI->getOperand(2);
11497
11498 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11499 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11500 EI->getOperand(0)->getType() == V->getType()) {
11501 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011502 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11503 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011504
11505 // Either the extracted from or inserted into vector must be RHSVec,
11506 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011507 if (EI->getOperand(0) == RHS || RHS == 0) {
11508 RHS = EI->getOperand(0);
11509 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011510 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011511 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011512 return V;
11513 }
11514
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011515 if (VecOp == RHS) {
11516 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011517 // Everything but the extracted element is replaced with the RHS.
11518 for (unsigned i = 0; i != NumElts; ++i) {
11519 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011520 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011521 }
11522 return V;
11523 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011524
11525 // If this insertelement is a chain that comes from exactly these two
11526 // vectors, return the vector and the effective shuffle.
11527 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11528 return EI->getOperand(0);
11529
Chris Lattnerefb47352006-04-15 01:39:45 +000011530 }
11531 }
11532 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011533 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011534
11535 // Otherwise, can't do anything fancy. Return an identity vector.
11536 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011537 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011538 return V;
11539}
11540
11541Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11542 Value *VecOp = IE.getOperand(0);
11543 Value *ScalarOp = IE.getOperand(1);
11544 Value *IdxOp = IE.getOperand(2);
11545
Chris Lattner599ded12007-04-09 01:11:16 +000011546 // Inserting an undef or into an undefined place, remove this.
11547 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11548 ReplaceInstUsesWith(IE, VecOp);
11549
Chris Lattnerefb47352006-04-15 01:39:45 +000011550 // If the inserted element was extracted from some other vector, and if the
11551 // indexes are constant, try to turn this into a shufflevector operation.
11552 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11553 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11554 EI->getOperand(0)->getType() == IE.getType()) {
11555 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011556 unsigned ExtractedIdx =
11557 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011558 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011559
11560 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11561 return ReplaceInstUsesWith(IE, VecOp);
11562
11563 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11564 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11565
11566 // If we are extracting a value from a vector, then inserting it right
11567 // back into the same place, just use the input vector.
11568 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11569 return ReplaceInstUsesWith(IE, VecOp);
11570
11571 // We could theoretically do this for ANY input. However, doing so could
11572 // turn chains of insertelement instructions into a chain of shufflevector
11573 // instructions, and right now we do not merge shufflevectors. As such,
11574 // only do this in a situation where it is clear that there is benefit.
11575 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11576 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11577 // the values of VecOp, except then one read from EIOp0.
11578 // Build a new shuffle mask.
11579 std::vector<Constant*> Mask;
11580 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011581 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011582 else {
11583 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011584 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011585 NumVectorElts));
11586 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011587 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011588 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011589 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011590 }
11591
11592 // If this insertelement isn't used by some other insertelement, turn it
11593 // (and any insertelements it points to), into one big shuffle.
11594 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11595 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011596 Value *RHS = 0;
11597 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11598 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11599 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011600 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011601 }
11602 }
11603 }
11604
11605 return 0;
11606}
11607
11608
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011609Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11610 Value *LHS = SVI.getOperand(0);
11611 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011612 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011613
11614 bool MadeChange = false;
11615
Chris Lattner867b99f2006-10-05 06:55:50 +000011616 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011617 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011618 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11619
Chris Lattnere4929dd2007-01-05 07:36:08 +000011620 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011621 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011622 if (isa<UndefValue>(SVI.getOperand(1))) {
11623 // Scan to see if there are any references to the RHS. If so, replace them
11624 // with undef element refs and set MadeChange to true.
11625 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11626 if (Mask[i] >= e && Mask[i] != 2*e) {
11627 Mask[i] = 2*e;
11628 MadeChange = true;
11629 }
11630 }
11631
11632 if (MadeChange) {
11633 // Remap any references to RHS to use LHS.
11634 std::vector<Constant*> Elts;
11635 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11636 if (Mask[i] == 2*e)
11637 Elts.push_back(UndefValue::get(Type::Int32Ty));
11638 else
11639 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11640 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011641 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011642 }
11643 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011644
Chris Lattner863bcff2006-05-25 23:48:38 +000011645 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11646 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11647 if (LHS == RHS || isa<UndefValue>(LHS)) {
11648 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011649 // shuffle(undef,undef,mask) -> undef.
11650 return ReplaceInstUsesWith(SVI, LHS);
11651 }
11652
Chris Lattner863bcff2006-05-25 23:48:38 +000011653 // Remap any references to RHS to use LHS.
11654 std::vector<Constant*> Elts;
11655 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011656 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011657 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011658 else {
11659 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11660 (Mask[i] < e && isa<UndefValue>(LHS)))
11661 Mask[i] = 2*e; // Turn into undef.
11662 else
11663 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011664 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011665 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011666 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011667 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011668 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011669 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011670 LHS = SVI.getOperand(0);
11671 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011672 MadeChange = true;
11673 }
11674
Chris Lattner7b2e27922006-05-26 00:29:06 +000011675 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011676 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011677
Chris Lattner863bcff2006-05-25 23:48:38 +000011678 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11679 if (Mask[i] >= e*2) continue; // Ignore undef values.
11680 // Is this an identity shuffle of the LHS value?
11681 isLHSID &= (Mask[i] == i);
11682
11683 // Is this an identity shuffle of the RHS value?
11684 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011685 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011686
Chris Lattner863bcff2006-05-25 23:48:38 +000011687 // Eliminate identity shuffles.
11688 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11689 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011690
Chris Lattner7b2e27922006-05-26 00:29:06 +000011691 // If the LHS is a shufflevector itself, see if we can combine it with this
11692 // one without producing an unusual shuffle. Here we are really conservative:
11693 // we are absolutely afraid of producing a shuffle mask not in the input
11694 // program, because the code gen may not be smart enough to turn a merged
11695 // shuffle into two specific shuffles: it may produce worse code. As such,
11696 // we only merge two shuffles if the result is one of the two input shuffle
11697 // masks. In this case, merging the shuffles just removes one instruction,
11698 // which we know is safe. This is good for things like turning:
11699 // (splat(splat)) -> splat.
11700 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11701 if (isa<UndefValue>(RHS)) {
11702 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11703
11704 std::vector<unsigned> NewMask;
11705 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11706 if (Mask[i] >= 2*e)
11707 NewMask.push_back(2*e);
11708 else
11709 NewMask.push_back(LHSMask[Mask[i]]);
11710
11711 // If the result mask is equal to the src shuffle or this shuffle mask, do
11712 // the replacement.
11713 if (NewMask == LHSMask || NewMask == Mask) {
11714 std::vector<Constant*> Elts;
11715 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11716 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011717 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011718 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011719 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011720 }
11721 }
11722 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11723 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011724 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011725 }
11726 }
11727 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011728
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011729 return MadeChange ? &SVI : 0;
11730}
11731
11732
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011733
Chris Lattnerea1c4542004-12-08 23:43:58 +000011734
11735/// TryToSinkInstruction - Try to move the specified instruction from its
11736/// current block into the beginning of DestBlock, which can only happen if it's
11737/// safe to move the instruction past all of the instructions between it and the
11738/// end of its block.
11739static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11740 assert(I->hasOneUse() && "Invariants didn't hold!");
11741
Chris Lattner108e9022005-10-27 17:13:11 +000011742 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011743 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11744 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011745
Chris Lattnerea1c4542004-12-08 23:43:58 +000011746 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011747 if (isa<AllocaInst>(I) && I->getParent() ==
11748 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011749 return false;
11750
Chris Lattner96a52a62004-12-09 07:14:34 +000011751 // We can only sink load instructions if there is nothing between the load and
11752 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011753 if (I->mayReadFromMemory()) {
11754 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011755 Scan != E; ++Scan)
11756 if (Scan->mayWriteToMemory())
11757 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011758 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011759
11760 BasicBlock::iterator InsertPos = DestBlock->begin();
11761 while (isa<PHINode>(InsertPos)) ++InsertPos;
11762
Chris Lattner4bc5f802005-08-08 19:11:57 +000011763 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011764 ++NumSunkInst;
11765 return true;
11766}
11767
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011768
11769/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11770/// all reachable code to the worklist.
11771///
11772/// This has a couple of tricks to make the code faster and more powerful. In
11773/// particular, we constant fold and DCE instructions as we go, to avoid adding
11774/// them to the worklist (this significantly speeds up instcombine on code where
11775/// many instructions are dead or constant). Additionally, if we find a branch
11776/// whose condition is a known constant, we only visit the reachable successors.
11777///
11778static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011779 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011780 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011781 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011782 std::vector<BasicBlock*> Worklist;
11783 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011784
Chris Lattner2c7718a2007-03-23 19:17:18 +000011785 while (!Worklist.empty()) {
11786 BB = Worklist.back();
11787 Worklist.pop_back();
11788
11789 // We have now visited this block! If we've already been here, ignore it.
11790 if (!Visited.insert(BB)) continue;
11791
11792 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11793 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011794
Chris Lattner2c7718a2007-03-23 19:17:18 +000011795 // DCE instruction if trivially dead.
11796 if (isInstructionTriviallyDead(Inst)) {
11797 ++NumDeadInst;
11798 DOUT << "IC: DCE: " << *Inst;
11799 Inst->eraseFromParent();
11800 continue;
11801 }
11802
11803 // ConstantProp instruction if trivially constant.
11804 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11805 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11806 Inst->replaceAllUsesWith(C);
11807 ++NumConstProp;
11808 Inst->eraseFromParent();
11809 continue;
11810 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011811
Chris Lattner2c7718a2007-03-23 19:17:18 +000011812 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011813 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011814
11815 // Recursively visit successors. If this is a branch or switch on a
11816 // constant, only visit the reachable successor.
11817 TerminatorInst *TI = BB->getTerminator();
11818 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11819 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11820 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011821 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011822 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011823 continue;
11824 }
11825 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11826 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11827 // See if this is an explicit destination.
11828 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11829 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011830 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011831 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011832 continue;
11833 }
11834
11835 // Otherwise it is the default destination.
11836 Worklist.push_back(SI->getSuccessor(0));
11837 continue;
11838 }
11839 }
11840
11841 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11842 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011843 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011844}
11845
Chris Lattnerec9c3582007-03-03 02:04:50 +000011846bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011847 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011848 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011849
11850 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11851 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011852
Chris Lattnerb3d59702005-07-07 20:40:38 +000011853 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011854 // Do a depth-first traversal of the function, populate the worklist with
11855 // the reachable instructions. Ignore blocks that are not reachable. Keep
11856 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011857 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011858 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011859
Chris Lattnerb3d59702005-07-07 20:40:38 +000011860 // Do a quick scan over the function. If we find any blocks that are
11861 // unreachable, remove any instructions inside of them. This prevents
11862 // the instcombine code from having to deal with some bad special cases.
11863 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11864 if (!Visited.count(BB)) {
11865 Instruction *Term = BB->getTerminator();
11866 while (Term != BB->begin()) { // Remove instrs bottom-up
11867 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011868
Bill Wendlingb7427032006-11-26 09:46:52 +000011869 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011870 ++NumDeadInst;
11871
11872 if (!I->use_empty())
11873 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11874 I->eraseFromParent();
11875 }
11876 }
11877 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011878
Chris Lattnerdbab3862007-03-02 21:28:56 +000011879 while (!Worklist.empty()) {
11880 Instruction *I = RemoveOneFromWorkList();
11881 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011882
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011883 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011884 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011885 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011886 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011887 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011888 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011889
Bill Wendlingb7427032006-11-26 09:46:52 +000011890 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011891
11892 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011893 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011894 continue;
11895 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011896
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011897 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011898 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011899 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011900
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011901 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011902 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011903 ReplaceInstUsesWith(*I, C);
11904
Chris Lattner62b14df2002-09-02 04:59:56 +000011905 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011906 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011907 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011908 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011909 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011910
Chris Lattnerea1c4542004-12-08 23:43:58 +000011911 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011912 // FIXME: Remove GetResultInst test when first class support for aggregates
11913 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011914 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011915 BasicBlock *BB = I->getParent();
11916 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11917 if (UserParent != BB) {
11918 bool UserIsSuccessor = false;
11919 // See if the user is one of our successors.
11920 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11921 if (*SI == UserParent) {
11922 UserIsSuccessor = true;
11923 break;
11924 }
11925
11926 // If the user is one of our immediate successors, and if that successor
11927 // only has us as a predecessors (we'd have to split the critical edge
11928 // otherwise), we can keep going.
11929 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11930 next(pred_begin(UserParent)) == pred_end(UserParent))
11931 // Okay, the CFG is simple enough, try to sink this instruction.
11932 Changed |= TryToSinkInstruction(I, UserParent);
11933 }
11934 }
11935
Chris Lattner8a2a3112001-12-14 16:52:21 +000011936 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011937#ifndef NDEBUG
11938 std::string OrigI;
11939#endif
11940 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011941 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011942 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011943 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011944 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011945 DOUT << "IC: Old = " << *I
11946 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011947
Chris Lattnerf523d062004-06-09 05:08:07 +000011948 // Everything uses the new instruction now.
11949 I->replaceAllUsesWith(Result);
11950
11951 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011952 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011953 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011954
Chris Lattner6934a042007-02-11 01:23:03 +000011955 // Move the name to the new instruction first.
11956 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011957
11958 // Insert the new instruction into the basic block...
11959 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011960 BasicBlock::iterator InsertPos = I;
11961
11962 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11963 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11964 ++InsertPos;
11965
11966 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011967
Chris Lattner00d51312004-05-01 23:27:23 +000011968 // Make sure that we reprocess all operands now that we reduced their
11969 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011970 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011971
Chris Lattnerf523d062004-06-09 05:08:07 +000011972 // Instructions can end up on the worklist more than once. Make sure
11973 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011974 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011975
11976 // Erase the old instruction.
11977 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011978 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011979#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011980 DOUT << "IC: Mod = " << OrigI
11981 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011982#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011983
Chris Lattner90ac28c2002-08-02 19:29:35 +000011984 // If the instruction was modified, it's possible that it is now dead.
11985 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011986 if (isInstructionTriviallyDead(I)) {
11987 // Make sure we process all operands now that we are reducing their
11988 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011989 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011990
Chris Lattner00d51312004-05-01 23:27:23 +000011991 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011992 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011993 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011994 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011995 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011996 AddToWorkList(I);
11997 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011998 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011999 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012000 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012001 }
12002 }
12003
Chris Lattnerec9c3582007-03-03 02:04:50 +000012004 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000012005
12006 // Do an explicit clear, this shrinks the map if needed.
12007 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012008 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012009}
12010
Chris Lattnerec9c3582007-03-03 02:04:50 +000012011
12012bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012013 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12014
Chris Lattnerec9c3582007-03-03 02:04:50 +000012015 bool EverMadeChange = false;
12016
12017 // Iterate while there is work to do.
12018 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012019 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012020 EverMadeChange = true;
12021 return EverMadeChange;
12022}
12023
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012024FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012025 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012026}
Brian Gaeked0fde302003-11-11 22:41:34 +000012027