blob: 1a8786810561787727bc7e7fd4f2a9f202f6b9e9 [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;
Dan Gohmana332f172008-05-23 02:28:01 +00002075 unsigned FirstAnswer = 1;
Dan Gohman45b4e482008-05-19 22:14:15 +00002076
2077 if (Depth == 6)
2078 return 1; // Limit search depth.
2079
2080 User *U = dyn_cast<User>(V);
2081 switch (getOpcode(V)) {
2082 default: break;
2083 case Instruction::SExt:
2084 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2085 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2086
2087 case Instruction::AShr:
2088 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002089 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002090 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2091 Tmp += C->getZExtValue();
2092 if (Tmp > TyBits) Tmp = TyBits;
2093 }
2094 return Tmp;
2095 case Instruction::Shl:
2096 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2097 // shl destroys sign bits.
2098 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2099 if (C->getZExtValue() >= TyBits || // Bad shift.
2100 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2101 return Tmp - C->getZExtValue();
2102 }
2103 break;
2104 case Instruction::And:
2105 case Instruction::Or:
Dan Gohmana332f172008-05-23 02:28:01 +00002106 case Instruction::Xor: // NOT is handled here.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002107 // Logical binary ops preserve the number of sign bits at the worst.
2108 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2109 if (Tmp != 1) {
2110 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohmana332f172008-05-23 02:28:01 +00002111 FirstAnswer = std::min(Tmp, Tmp2);
2112 // We computed what we know about the sign bits as our first
2113 // answer. Now proceed to the generic code that uses
2114 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002115 }
Dan Gohmana332f172008-05-23 02:28:01 +00002116 break;
Dan Gohman45b4e482008-05-19 22:14:15 +00002117
2118 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002119 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002120 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002121 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002122 return std::min(Tmp, Tmp2);
2123
2124 case Instruction::Add:
2125 // Add can have at most one carry bit. Thus we know that the output
2126 // is, at worst, one more bit than the inputs.
2127 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2128 if (Tmp == 1) return 1; // Early out.
2129
2130 // Special case decrementing a value (ADD X, -1):
2131 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2132 if (CRHS->isAllOnesValue()) {
2133 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2134 APInt Mask = APInt::getAllOnesValue(TyBits);
2135 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2136
2137 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2138 // sign bits set.
2139 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2140 return TyBits;
2141
2142 // If we are subtracting one from a positive number, there is no carry
2143 // out of the result.
2144 if (KnownZero.isNegative())
2145 return Tmp;
2146 }
2147
2148 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2149 if (Tmp2 == 1) return 1;
2150 return std::min(Tmp, Tmp2)-1;
2151 break;
2152
2153 case Instruction::Sub:
2154 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2155 if (Tmp2 == 1) return 1;
2156
2157 // Handle NEG.
2158 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2159 if (CLHS->isNullValue()) {
2160 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2161 APInt Mask = APInt::getAllOnesValue(TyBits);
2162 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2163 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2164 // sign bits set.
2165 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2166 return TyBits;
2167
2168 // If the input is known to be positive (the sign bit is known clear),
2169 // the output of the NEG has the same number of sign bits as the input.
2170 if (KnownZero.isNegative())
2171 return Tmp2;
2172
2173 // Otherwise, we treat this like a SUB.
2174 }
2175
2176 // Sub can have at most one carry bit. Thus we know that the output
2177 // is, at worst, one more bit than the inputs.
2178 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2179 if (Tmp == 1) return 1; // Early out.
2180 return std::min(Tmp, Tmp2)-1;
2181 break;
2182 case Instruction::Trunc:
2183 // FIXME: it's tricky to do anything useful for this, but it is an important
2184 // case for targets like X86.
2185 break;
2186 }
2187
2188 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2189 // use this information.
2190 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2191 APInt Mask = APInt::getAllOnesValue(TyBits);
2192 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2193
2194 if (KnownZero.isNegative()) { // sign bit is 0
2195 Mask = KnownZero;
2196 } else if (KnownOne.isNegative()) { // sign bit is 1;
2197 Mask = KnownOne;
2198 } else {
2199 // Nothing known.
Dan Gohmana332f172008-05-23 02:28:01 +00002200 return FirstAnswer;
Dan Gohman45b4e482008-05-19 22:14:15 +00002201 }
2202
2203 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2204 // the number of identical bits in the top of the input value.
2205 Mask = ~Mask;
2206 Mask <<= Mask.getBitWidth()-TyBits;
2207 // Return # leading zeros. We use 'min' here in case Val was zero before
2208 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohmana332f172008-05-23 02:28:01 +00002209 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman45b4e482008-05-19 22:14:15 +00002210}
2211
2212
Chris Lattner564a7272003-08-13 19:01:45 +00002213/// AssociativeOpt - Perform an optimization on an associative operator. This
2214/// function is designed to check a chain of associative operators for a
2215/// potential to apply a certain optimization. Since the optimization may be
2216/// applicable if the expression was reassociated, this checks the chain, then
2217/// reassociates the expression as necessary to expose the optimization
2218/// opportunity. This makes use of a special Functor, which must define
2219/// 'shouldApply' and 'apply' methods.
2220///
2221template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002222static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002223 unsigned Opcode = Root.getOpcode();
2224 Value *LHS = Root.getOperand(0);
2225
2226 // Quick check, see if the immediate LHS matches...
2227 if (F.shouldApply(LHS))
2228 return F.apply(Root);
2229
2230 // Otherwise, if the LHS is not of the same opcode as the root, return.
2231 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002232 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002233 // Should we apply this transform to the RHS?
2234 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2235
2236 // If not to the RHS, check to see if we should apply to the LHS...
2237 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2238 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2239 ShouldApply = true;
2240 }
2241
2242 // If the functor wants to apply the optimization to the RHS of LHSI,
2243 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2244 if (ShouldApply) {
2245 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002246
Chris Lattner564a7272003-08-13 19:01:45 +00002247 // Now all of the instructions are in the current basic block, go ahead
2248 // and perform the reassociation.
2249 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2250
2251 // First move the selected RHS to the LHS of the root...
2252 Root.setOperand(0, LHSI->getOperand(1));
2253
2254 // Make what used to be the LHS of the root be the user of the root...
2255 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002256 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002257 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2258 return 0;
2259 }
Chris Lattner65725312004-04-16 18:08:07 +00002260 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002261 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002262 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2263 BasicBlock::iterator ARI = &Root; ++ARI;
2264 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2265 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002266
2267 // Now propagate the ExtraOperand down the chain of instructions until we
2268 // get to LHSI.
2269 while (TmpLHSI != LHSI) {
2270 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002271 // Move the instruction to immediately before the chain we are
2272 // constructing to avoid breaking dominance properties.
2273 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2274 BB->getInstList().insert(ARI, NextLHSI);
2275 ARI = NextLHSI;
2276
Chris Lattner564a7272003-08-13 19:01:45 +00002277 Value *NextOp = NextLHSI->getOperand(1);
2278 NextLHSI->setOperand(1, ExtraOperand);
2279 TmpLHSI = NextLHSI;
2280 ExtraOperand = NextOp;
2281 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002282
Chris Lattner564a7272003-08-13 19:01:45 +00002283 // Now that the instructions are reassociated, have the functor perform
2284 // the transformation...
2285 return F.apply(Root);
2286 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002287
Chris Lattner564a7272003-08-13 19:01:45 +00002288 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2289 }
2290 return 0;
2291}
2292
Dan Gohman844731a2008-05-13 00:00:25 +00002293namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002294
Nick Lewycky8539fe22008-05-23 04:14:51 +00002295// AddRHS - Implements: X + X --> X << 1 and X + X --> X * 2 for vectors
Chris Lattner564a7272003-08-13 19:01:45 +00002296struct AddRHS {
2297 Value *RHS;
2298 AddRHS(Value *rhs) : RHS(rhs) {}
2299 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2300 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky8539fe22008-05-23 04:14:51 +00002301 if (Add.getType()->getTypeID() == Type::VectorTyID) {
2302 const VectorType *VTy = cast<VectorType>(Add.getType());
2303 ConstantInt *CI = ConstantInt::get(VTy->getElementType(), 2);
2304 std::vector<Constant*> Elts(VTy->getNumElements(), CI);
2305 return BinaryOperator::CreateMul(Add.getOperand(0),
2306 ConstantVector::get(Elts));
2307 } else {
2308 return BinaryOperator::CreateShl(Add.getOperand(0),
2309 ConstantInt::get(Add.getType(), 1));
2310 }
Chris Lattner564a7272003-08-13 19:01:45 +00002311 }
2312};
2313
2314// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2315// iff C1&C2 == 0
2316struct AddMaskingAnd {
2317 Constant *C2;
2318 AddMaskingAnd(Constant *c) : C2(c) {}
2319 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002320 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002321 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002322 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002323 }
2324 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002325 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002326 }
2327};
2328
Dan Gohman844731a2008-05-13 00:00:25 +00002329}
2330
Chris Lattner6e7ba452005-01-01 16:22:27 +00002331static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002332 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002333 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002334 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002335 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002336
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002337 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002338 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002339 }
2340
Chris Lattner2eefe512004-04-09 19:05:30 +00002341 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002342 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2343 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002344
Chris Lattner2eefe512004-04-09 19:05:30 +00002345 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2346 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002347 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2348 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002349 }
2350
2351 Value *Op0 = SO, *Op1 = ConstOperand;
2352 if (!ConstIsRHS)
2353 std::swap(Op0, Op1);
2354 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002355 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002356 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002357 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002358 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002359 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002360 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002361 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002362 abort();
2363 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002364 return IC->InsertNewInstBefore(New, I);
2365}
2366
2367// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2368// constant as the other operand, try to fold the binary operator into the
2369// select arguments. This also works for Cast instructions, which obviously do
2370// not have a second operand.
2371static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2372 InstCombiner *IC) {
2373 // Don't modify shared select instructions
2374 if (!SI->hasOneUse()) return 0;
2375 Value *TV = SI->getOperand(1);
2376 Value *FV = SI->getOperand(2);
2377
2378 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002379 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002380 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002381
Chris Lattner6e7ba452005-01-01 16:22:27 +00002382 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2383 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2384
Gabor Greif051a9502008-04-06 20:25:17 +00002385 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2386 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002387 }
2388 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002389}
2390
Chris Lattner4e998b22004-09-29 05:07:12 +00002391
2392/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2393/// node as operand #0, see if we can fold the instruction into the PHI (which
2394/// is only possible if all operands to the PHI are constants).
2395Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2396 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002397 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002398 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002399
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002400 // Check to see if all of the operands of the PHI are constants. If there is
2401 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002402 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002403 BasicBlock *NonConstBB = 0;
2404 for (unsigned i = 0; i != NumPHIValues; ++i)
2405 if (!isa<Constant>(PN->getIncomingValue(i))) {
2406 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002407 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002408 NonConstBB = PN->getIncomingBlock(i);
2409
2410 // If the incoming non-constant value is in I's block, we have an infinite
2411 // loop.
2412 if (NonConstBB == I.getParent())
2413 return 0;
2414 }
2415
2416 // If there is exactly one non-constant value, we can insert a copy of the
2417 // operation in that block. However, if this is a critical edge, we would be
2418 // inserting the computation one some other paths (e.g. inside a loop). Only
2419 // do this if the pred block is unconditionally branching into the phi block.
2420 if (NonConstBB) {
2421 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2422 if (!BI || !BI->isUnconditional()) return 0;
2423 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002424
2425 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002426 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002427 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002428 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002429 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002430
2431 // Next, add all of the operands to the PHI.
2432 if (I.getNumOperands() == 2) {
2433 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002434 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002435 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002436 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002437 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2438 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2439 else
2440 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002441 } else {
2442 assert(PN->getIncomingBlock(i) == NonConstBB);
2443 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002444 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002445 PN->getIncomingValue(i), C, "phitmp",
2446 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002447 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002448 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002449 CI->getPredicate(),
2450 PN->getIncomingValue(i), C, "phitmp",
2451 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002452 else
2453 assert(0 && "Unknown binop!");
2454
Chris Lattnerdbab3862007-03-02 21:28:56 +00002455 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002456 }
2457 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002458 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002459 } else {
2460 CastInst *CI = cast<CastInst>(&I);
2461 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002462 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002463 Value *InV;
2464 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002465 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002466 } else {
2467 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002468 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002469 I.getType(), "phitmp",
2470 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002471 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002472 }
2473 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002474 }
2475 }
2476 return ReplaceInstUsesWith(I, NewPN);
2477}
2478
Chris Lattner2454a2e2008-01-29 06:52:45 +00002479
2480/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2481/// value is never equal to -0.0.
2482///
2483/// Note that this function will need to be revisited when we support nondefault
2484/// rounding modes!
2485///
2486static bool CannotBeNegativeZero(const Value *V) {
2487 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2488 return !CFP->getValueAPF().isNegZero();
2489
Chris Lattner2454a2e2008-01-29 06:52:45 +00002490 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002491 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002492 if (I->getOpcode() == Instruction::Add &&
2493 isa<ConstantFP>(I->getOperand(1)) &&
2494 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2495 return true;
2496
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002497 // sitofp and uitofp turn into +0.0 for zero.
2498 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2499 return true;
2500
Chris Lattner2454a2e2008-01-29 06:52:45 +00002501 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2502 if (II->getIntrinsicID() == Intrinsic::sqrt)
2503 return CannotBeNegativeZero(II->getOperand(1));
2504
2505 if (const CallInst *CI = dyn_cast<CallInst>(I))
2506 if (const Function *F = CI->getCalledFunction()) {
2507 if (F->isDeclaration()) {
2508 switch (F->getNameLen()) {
2509 case 3: // abs(x) != -0.0
2510 if (!strcmp(F->getNameStart(), "abs")) return true;
2511 break;
2512 case 4: // abs[lf](x) != -0.0
2513 if (!strcmp(F->getNameStart(), "absf")) return true;
2514 if (!strcmp(F->getNameStart(), "absl")) return true;
2515 break;
2516 }
2517 }
2518 }
2519 }
2520
2521 return false;
2522}
2523
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002524/// WillNotOverflowSignedAdd - Return true if we can prove that:
2525/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2526/// This basically requires proving that the add in the original type would not
2527/// overflow to change the sign bit or have a carry out.
2528bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2529 // There are different heuristics we can use for this. Here are some simple
2530 // ones.
2531
2532 // Add has the property that adding any two 2's complement numbers can only
2533 // have one carry bit which can change a sign. As such, if LHS and RHS each
2534 // have at least two sign bits, we know that the addition of the two values will
2535 // sign extend fine.
2536 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2537 return true;
2538
2539
2540 // If one of the operands only has one non-zero bit, and if the other operand
2541 // has a known-zero bit in a more significant place than it (not including the
2542 // sign bit) the ripple may go up to and fill the zero, but won't change the
2543 // sign. For example, (X & ~4) + 1.
2544
2545 // TODO: Implement.
2546
2547 return false;
2548}
2549
Chris Lattner2454a2e2008-01-29 06:52:45 +00002550
Chris Lattner7e708292002-06-25 16:13:24 +00002551Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002552 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002553 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002554
Chris Lattner66331a42004-04-10 22:01:55 +00002555 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002556 // X + undef -> undef
2557 if (isa<UndefValue>(RHS))
2558 return ReplaceInstUsesWith(I, RHS);
2559
Chris Lattner66331a42004-04-10 22:01:55 +00002560 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002561 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002562 if (RHSC->isNullValue())
2563 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002564 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002565 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2566 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002567 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002568 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002569
Chris Lattner66331a42004-04-10 22:01:55 +00002570 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002571 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002572 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002573 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002574 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002575 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002576
2577 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2578 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002579 if (!isa<VectorType>(I.getType())) {
2580 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2581 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2582 KnownZero, KnownOne))
2583 return &I;
2584 }
Chris Lattner66331a42004-04-10 22:01:55 +00002585 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002586
2587 if (isa<PHINode>(LHS))
2588 if (Instruction *NV = FoldOpIntoPhi(I))
2589 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002590
Chris Lattner4f637d42006-01-06 17:59:59 +00002591 ConstantInt *XorRHS = 0;
2592 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002593 if (isa<ConstantInt>(RHSC) &&
2594 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002595 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002596 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002597
Zhou Sheng4351c642007-04-02 08:20:41 +00002598 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002599 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2600 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002601 do {
2602 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002603 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2604 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002605 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2606 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002607 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002608 if (!MaskedValueIsZero(XorLHS,
2609 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002610 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002611 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002612 }
2613 }
2614 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002615 C0080Val = APIntOps::lshr(C0080Val, Size);
2616 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2617 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002618
Reid Spencer35c38852007-03-28 01:36:16 +00002619 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002620 // with funny bit widths then this switch statement should be removed. It
2621 // is just here to get the size of the "middle" type back up to something
2622 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002623 const Type *MiddleType = 0;
2624 switch (Size) {
2625 default: break;
2626 case 32: MiddleType = Type::Int32Ty; break;
2627 case 16: MiddleType = Type::Int16Ty; break;
2628 case 8: MiddleType = Type::Int8Ty; break;
2629 }
2630 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002631 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002632 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002633 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002634 }
2635 }
Chris Lattner66331a42004-04-10 22:01:55 +00002636 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002637
Nick Lewycky8539fe22008-05-23 04:14:51 +00002638 // X + X --> X << 1 and X + X --> X * 2 for vectors
2639 if (I.getType()->isIntOrIntVector() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002640 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002641
2642 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2643 if (RHSI->getOpcode() == Instruction::Sub)
2644 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2645 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2646 }
2647 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2648 if (LHSI->getOpcode() == Instruction::Sub)
2649 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2650 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2651 }
Robert Bocchino71698282004-07-27 21:02:21 +00002652 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002653
Chris Lattner5c4afb92002-05-08 22:46:53 +00002654 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002655 // -A + -B --> -(A + B)
2656 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002657 if (LHS->getType()->isIntOrIntVector()) {
2658 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002659 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002660 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002661 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002662 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002663 }
2664
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002665 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002666 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002667
2668 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002669 if (!isa<Constant>(RHS))
2670 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002671 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002672
Misha Brukmanfd939082005-04-21 23:48:37 +00002673
Chris Lattner50af16a2004-11-13 19:50:12 +00002674 ConstantInt *C2;
2675 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2676 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002677 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002678
2679 // X*C1 + X*C2 --> X * (C1+C2)
2680 ConstantInt *C1;
2681 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002682 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002683 }
2684
2685 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002686 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002687 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002688
Chris Lattnere617c9e2007-01-05 02:17:46 +00002689 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002690 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2691 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002692
Chris Lattnerad3448c2003-02-18 19:57:07 +00002693
Chris Lattner564a7272003-08-13 19:01:45 +00002694 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002695 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002696 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2697 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002698
2699 // A+B --> A|B iff A and B have no bits set in common.
2700 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2701 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2702 APInt LHSKnownOne(IT->getBitWidth(), 0);
2703 APInt LHSKnownZero(IT->getBitWidth(), 0);
2704 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2705 if (LHSKnownZero != 0) {
2706 APInt RHSKnownOne(IT->getBitWidth(), 0);
2707 APInt RHSKnownZero(IT->getBitWidth(), 0);
2708 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2709
2710 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002711 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002712 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002713 }
2714 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002715
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002716 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002717 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002718 Value *W, *X, *Y, *Z;
2719 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2720 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2721 if (W != Y) {
2722 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002723 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002724 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002725 std::swap(W, X);
2726 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002727 std::swap(Y, Z);
2728 std::swap(W, X);
2729 }
2730 }
2731
2732 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002733 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002734 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002735 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002736 }
2737 }
2738 }
2739
Chris Lattner6b032052003-10-02 15:11:26 +00002740 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002741 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002742 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002743 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002744
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002745 // (X & FF00) + xx00 -> (X+xx00) & FF00
2746 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002747 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002748 if (Anded == CRHS) {
2749 // See if all bits from the first bit set in the Add RHS up are included
2750 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002751 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002752
2753 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002754 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002755
2756 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002757 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002758
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002759 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2760 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002761 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002762 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002763 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002764 }
2765 }
2766 }
2767
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002768 // Try to fold constant add into select arguments.
2769 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002770 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002771 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002772 }
2773
Reid Spencer1628cec2006-10-26 06:15:43 +00002774 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002775 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002776 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002777 CastInst *CI = dyn_cast<CastInst>(LHS);
2778 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002779 if (!CI) {
2780 CI = dyn_cast<CastInst>(RHS);
2781 Other = LHS;
2782 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002783 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002784 (CI->getType()->getPrimitiveSizeInBits() ==
2785 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002786 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002787 unsigned AS =
2788 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002789 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2790 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002791 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002792 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002793 }
2794 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002795
Chris Lattner42790482007-12-20 01:56:58 +00002796 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002797 {
2798 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2799 Value *Other = RHS;
2800 if (!SI) {
2801 SI = dyn_cast<SelectInst>(RHS);
2802 Other = LHS;
2803 }
Chris Lattner42790482007-12-20 01:56:58 +00002804 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002805 Value *TV = SI->getTrueValue();
2806 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002807 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002808
2809 // Can we fold the add into the argument of the select?
2810 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002811 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2812 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002813 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002814 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2815 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002816 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002817 }
2818 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002819
2820 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2821 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2822 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2823 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002824
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002825 // Check for (add (sext x), y), see if we can merge this into an
2826 // integer add followed by a sext.
2827 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2828 // (add (sext x), cst) --> (sext (add x, cst'))
2829 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2830 Constant *CI =
2831 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2832 if (LHSConv->hasOneUse() &&
2833 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2834 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2835 // Insert the new, smaller add.
2836 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2837 CI, "addconv");
2838 InsertNewInstBefore(NewAdd, I);
2839 return new SExtInst(NewAdd, I.getType());
2840 }
2841 }
2842
2843 // (add (sext x), (sext y)) --> (sext (add int x, y))
2844 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2845 // Only do this if x/y have the same type, if at last one of them has a
2846 // single use (so we don't increase the number of sexts), and if the
2847 // integer add will not overflow.
2848 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2849 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2850 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2851 RHSConv->getOperand(0))) {
2852 // Insert the new integer add.
2853 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2854 RHSConv->getOperand(0),
2855 "addconv");
2856 InsertNewInstBefore(NewAdd, I);
2857 return new SExtInst(NewAdd, I.getType());
2858 }
2859 }
2860 }
2861
2862 // Check for (add double (sitofp x), y), see if we can merge this into an
2863 // integer add followed by a promotion.
2864 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2865 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2866 // ... if the constant fits in the integer value. This is useful for things
2867 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2868 // requires a constant pool load, and generally allows the add to be better
2869 // instcombined.
2870 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2871 Constant *CI =
2872 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2873 if (LHSConv->hasOneUse() &&
2874 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2875 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2876 // Insert the new integer add.
2877 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2878 CI, "addconv");
2879 InsertNewInstBefore(NewAdd, I);
2880 return new SIToFPInst(NewAdd, I.getType());
2881 }
2882 }
2883
2884 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2885 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2886 // Only do this if x/y have the same type, if at last one of them has a
2887 // single use (so we don't increase the number of int->fp conversions),
2888 // and if the integer add will not overflow.
2889 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2890 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2891 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2892 RHSConv->getOperand(0))) {
2893 // Insert the new integer add.
2894 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2895 RHSConv->getOperand(0),
2896 "addconv");
2897 InsertNewInstBefore(NewAdd, I);
2898 return new SIToFPInst(NewAdd, I.getType());
2899 }
2900 }
2901 }
2902
Chris Lattner7e708292002-06-25 16:13:24 +00002903 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002904}
2905
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002906// isSignBit - Return true if the value represented by the constant only has the
2907// highest order bit set.
2908static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002909 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002910 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002911}
2912
Chris Lattner7e708292002-06-25 16:13:24 +00002913Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002915
Chris Lattner233f7dc2002-08-12 21:17:25 +00002916 if (Op0 == Op1) // sub X, X -> 0
2917 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002918
Chris Lattner233f7dc2002-08-12 21:17:25 +00002919 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002920 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002921 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002922
Chris Lattnere87597f2004-10-16 18:11:37 +00002923 if (isa<UndefValue>(Op0))
2924 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2925 if (isa<UndefValue>(Op1))
2926 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2927
Chris Lattnerd65460f2003-11-05 01:06:05 +00002928 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2929 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002930 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002931 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002932
Chris Lattnerd65460f2003-11-05 01:06:05 +00002933 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002934 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002935 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002936 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002937
Chris Lattner76b7a062007-01-15 07:02:54 +00002938 // -(X >>u 31) -> (X >>s 31)
2939 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002940 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002941 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002942 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002943 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002944 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002945 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002946 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002947 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002948 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002949 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002950 }
2951 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002952 }
2953 else if (SI->getOpcode() == Instruction::AShr) {
2954 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2955 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002956 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002957 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002958 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002959 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002960 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002961 }
2962 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002963 }
2964 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002965 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002966
2967 // Try to fold constant sub into select arguments.
2968 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002969 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002970 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002971
2972 if (isa<PHINode>(Op0))
2973 if (Instruction *NV = FoldOpIntoPhi(I))
2974 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002975 }
2976
Chris Lattner43d84d62005-04-07 16:15:25 +00002977 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2978 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002979 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002980 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002981 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002982 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002983 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002984 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2985 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2986 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002987 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002988 Op1I->getOperand(0));
2989 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002990 }
2991
Chris Lattnerfd059242003-10-15 16:48:29 +00002992 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002993 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2994 // is not used by anyone else...
2995 //
Chris Lattner0517e722004-02-02 20:09:56 +00002996 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002997 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002998 // Swap the two operands of the subexpr...
2999 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
3000 Op1I->setOperand(0, IIOp1);
3001 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003002
Chris Lattnera2881962003-02-18 19:28:33 +00003003 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003004 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003005 }
3006
3007 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3008 //
3009 if (Op1I->getOpcode() == Instruction::And &&
3010 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3011 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3012
Chris Lattnerf523d062004-06-09 05:08:07 +00003013 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003014 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3015 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003016 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003017
Reid Spencerac5209e2006-10-16 23:08:08 +00003018 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003019 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003020 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003021 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003022 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003023 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003024 ConstantExpr::getNeg(DivRHS));
3025
Chris Lattnerad3448c2003-02-18 19:57:07 +00003026 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003027 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003028 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003029 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003031 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003032
3033 // X - ((X / Y) * Y) --> X % Y
3034 if (Op1I->getOpcode() == Instruction::Mul)
3035 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3036 if (Op0 == I->getOperand(0) &&
3037 Op1I->getOperand(1) == I->getOperand(1)) {
3038 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003039 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003040 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003041 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003042 }
Chris Lattner40371712002-05-09 01:29:19 +00003043 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003044 }
Chris Lattnera2881962003-02-18 19:28:33 +00003045
Chris Lattner9919e3d2006-12-02 00:13:08 +00003046 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003047 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003048 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003049 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3050 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3051 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3052 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003053 } else if (Op0I->getOpcode() == Instruction::Sub) {
3054 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003055 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003056 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003057 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003058
Chris Lattner50af16a2004-11-13 19:50:12 +00003059 ConstantInt *C1;
3060 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003061 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003062 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003063
Chris Lattner50af16a2004-11-13 19:50:12 +00003064 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3065 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003066 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003067 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003068 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003069}
3070
Chris Lattnera0141b92007-07-15 20:42:37 +00003071/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3072/// comparison only checks the sign bit. If it only checks the sign bit, set
3073/// TrueIfSigned if the result of the comparison is true when the input value is
3074/// signed.
3075static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3076 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003077 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003078 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3079 TrueIfSigned = true;
3080 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003081 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3082 TrueIfSigned = true;
3083 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003084 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3085 TrueIfSigned = false;
3086 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003087 case ICmpInst::ICMP_UGT:
3088 // True if LHS u> RHS and RHS == high-bit-mask - 1
3089 TrueIfSigned = true;
3090 return RHS->getValue() ==
3091 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3092 case ICmpInst::ICMP_UGE:
3093 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3094 TrueIfSigned = true;
3095 return RHS->getValue() ==
3096 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003097 default:
3098 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003099 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003100}
3101
Chris Lattner7e708292002-06-25 16:13:24 +00003102Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003103 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003104 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003105
Chris Lattnere87597f2004-10-16 18:11:37 +00003106 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3107 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3108
Chris Lattner233f7dc2002-08-12 21:17:25 +00003109 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003110 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3111 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003112
3113 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003114 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003115 if (SI->getOpcode() == Instruction::Shl)
3116 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003117 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003118 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003119
Zhou Sheng843f07672007-04-19 05:39:12 +00003120 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003121 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3122 if (CI->equalsInt(1)) // X * 1 == X
3123 return ReplaceInstUsesWith(I, Op0);
3124 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003125 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003126
Zhou Sheng97b52c22007-03-29 01:57:21 +00003127 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003128 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003129 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003130 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003131 }
Robert Bocchino71698282004-07-27 21:02:21 +00003132 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003133 if (Op1F->isNullValue())
3134 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003135
Chris Lattnera2881962003-02-18 19:28:33 +00003136 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3137 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003138 // We need a better interface for long double here.
3139 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3140 if (Op1F->isExactlyValue(1.0))
3141 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003142 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003143
3144 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3145 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003146 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003147 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003148 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003149 Op1, "tmp");
3150 InsertNewInstBefore(Add, I);
3151 Value *C1C2 = ConstantExpr::getMul(Op1,
3152 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003153 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003154
3155 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003156
3157 // Try to fold constant mul into select arguments.
3158 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003159 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003160 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003161
3162 if (isa<PHINode>(Op0))
3163 if (Instruction *NV = FoldOpIntoPhi(I))
3164 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003165 }
3166
Chris Lattnera4f445b2003-03-10 23:23:04 +00003167 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3168 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003169 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003170
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003171 // If one of the operands of the multiply is a cast from a boolean value, then
3172 // we know the bool is either zero or one, so this is a 'masking' multiply.
3173 // See if we can simplify things based on how the boolean was originally
3174 // formed.
3175 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003176 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003177 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003178 BoolCast = CI;
3179 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003180 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003181 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003182 BoolCast = CI;
3183 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003184 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003185 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3186 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003187 bool TIS = false;
3188
Reid Spencere4d87aa2006-12-23 06:05:41 +00003189 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003190 // multiply into a shift/and combination.
3191 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003192 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3193 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003194 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003195 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003196 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003197 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003198 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003199 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003200 BoolCast->getOperand(0)->getName()+
3201 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003202
3203 // If the multiply type is not the same as the source type, sign extend
3204 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003205 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003206 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3207 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003208 Instruction::CastOps opcode =
3209 (SrcBits == DstBits ? Instruction::BitCast :
3210 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3211 V = InsertCastBefore(opcode, V, I.getType(), I);
3212 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003213
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003214 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003215 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003216 }
3217 }
3218 }
3219
Chris Lattner7e708292002-06-25 16:13:24 +00003220 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003221}
3222
Reid Spencer1628cec2006-10-26 06:15:43 +00003223/// This function implements the transforms on div instructions that work
3224/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3225/// used by the visitors to those instructions.
3226/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003227Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003229
Chris Lattner50b2ca42008-02-19 06:12:18 +00003230 // undef / X -> 0 for integer.
3231 // undef / X -> undef for FP (the undef could be a snan).
3232 if (isa<UndefValue>(Op0)) {
3233 if (Op0->getType()->isFPOrFPVector())
3234 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003235 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003236 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003237
3238 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003239 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003240 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003241
Chris Lattner25feae52008-01-28 00:58:18 +00003242 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3243 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003244 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003245 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3246 // the same basic block, then we replace the select with Y, and the
3247 // condition of the select with false (if the cond value is in the same BB).
3248 // If the select has uses other than the div, this allows them to be
3249 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3250 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003251 if (ST->isNullValue()) {
3252 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3253 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003254 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003255 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3256 I.setOperand(1, SI->getOperand(2));
3257 else
3258 UpdateValueUsesWith(SI, SI->getOperand(2));
3259 return &I;
3260 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003261
Chris Lattner25feae52008-01-28 00:58:18 +00003262 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3263 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003264 if (ST->isNullValue()) {
3265 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3266 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003267 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003268 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3269 I.setOperand(1, SI->getOperand(1));
3270 else
3271 UpdateValueUsesWith(SI, SI->getOperand(1));
3272 return &I;
3273 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003274 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003275
Reid Spencer1628cec2006-10-26 06:15:43 +00003276 return 0;
3277}
Misha Brukmanfd939082005-04-21 23:48:37 +00003278
Reid Spencer1628cec2006-10-26 06:15:43 +00003279/// This function implements the transforms common to both integer division
3280/// instructions (udiv and sdiv). It is called by the visitors to those integer
3281/// division instructions.
3282/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003283Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003284 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3285
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003286 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003287 if (Op0 == Op1) {
3288 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3289 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3290 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3291 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3292 }
3293
3294 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3295 return ReplaceInstUsesWith(I, CI);
3296 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003297
Reid Spencer1628cec2006-10-26 06:15:43 +00003298 if (Instruction *Common = commonDivTransforms(I))
3299 return Common;
3300
3301 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3302 // div X, 1 == X
3303 if (RHS->equalsInt(1))
3304 return ReplaceInstUsesWith(I, Op0);
3305
3306 // (X / C1) / C2 -> X / (C1*C2)
3307 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3308 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3309 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003310 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3311 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3312 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003313 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003314 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003315 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003316
Reid Spencerbca0e382007-03-23 20:05:17 +00003317 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3320 return R;
3321 if (isa<PHINode>(Op0))
3322 if (Instruction *NV = FoldOpIntoPhi(I))
3323 return NV;
3324 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003325 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003326
Chris Lattnera2881962003-02-18 19:28:33 +00003327 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003328 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003329 if (LHS->equalsInt(0))
3330 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3331
Reid Spencer1628cec2006-10-26 06:15:43 +00003332 return 0;
3333}
3334
3335Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3336 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3337
3338 // Handle the integer div common cases
3339 if (Instruction *Common = commonIDivTransforms(I))
3340 return Common;
3341
3342 // X udiv C^2 -> X >> C
3343 // Check to see if this is an unsigned division with an exact power of 2,
3344 // if so, convert to a right shift.
3345 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003346 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003347 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003348 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003349 }
3350
3351 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003352 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003353 if (RHSI->getOpcode() == Instruction::Shl &&
3354 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003355 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003356 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003357 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003358 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003359 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003360 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003361 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003362 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003363 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003364 }
3365 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003366 }
3367
Reid Spencer1628cec2006-10-26 06:15:43 +00003368 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3369 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003370 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003371 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003372 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003373 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003374 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003375 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003376 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003377 // Construct the "on true" case of the select
3378 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003379 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003380 Op0, TC, SI->getName()+".t");
3381 TSI = InsertNewInstBefore(TSI, I);
3382
3383 // Construct the "on false" case of the select
3384 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003385 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003386 Op0, FC, SI->getName()+".f");
3387 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003388
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003389 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003390 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003391 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003392 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003393 return 0;
3394}
3395
Reid Spencer1628cec2006-10-26 06:15:43 +00003396Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3397 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3398
3399 // Handle the integer div common cases
3400 if (Instruction *Common = commonIDivTransforms(I))
3401 return Common;
3402
3403 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3404 // sdiv X, -1 == -X
3405 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003406 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003407
3408 // -X/C -> X/-C
3409 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003410 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003411 }
3412
3413 // If the sign bits of both operands are zero (i.e. we can prove they are
3414 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003415 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003416 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003417 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003418 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003419 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003420 }
3421 }
3422
3423 return 0;
3424}
3425
3426Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3427 return commonDivTransforms(I);
3428}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003429
Reid Spencer0a783f72006-11-02 01:53:59 +00003430/// This function implements the transforms on rem instructions that work
3431/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3432/// is used by the visitors to those instructions.
3433/// @brief Transforms common to all three rem instructions
3434Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003435 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003436
Chris Lattner50b2ca42008-02-19 06:12:18 +00003437 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003438 if (Constant *LHS = dyn_cast<Constant>(Op0))
3439 if (LHS->isNullValue())
3440 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3441
Chris Lattner50b2ca42008-02-19 06:12:18 +00003442 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3443 if (I.getType()->isFPOrFPVector())
3444 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003445 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003446 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003447 if (isa<UndefValue>(Op1))
3448 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003449
3450 // Handle cases involving: rem X, (select Cond, Y, Z)
3451 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3452 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3453 // the same basic block, then we replace the select with Y, and the
3454 // condition of the select with false (if the cond value is in the same
3455 // BB). If the select has uses other than the div, this allows them to be
3456 // simplified also.
3457 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3458 if (ST->isNullValue()) {
3459 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3460 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003461 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003462 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3463 I.setOperand(1, SI->getOperand(2));
3464 else
3465 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003466 return &I;
3467 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003468 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3469 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3470 if (ST->isNullValue()) {
3471 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3472 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003473 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003474 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3475 I.setOperand(1, SI->getOperand(1));
3476 else
3477 UpdateValueUsesWith(SI, SI->getOperand(1));
3478 return &I;
3479 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003480 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003481
Reid Spencer0a783f72006-11-02 01:53:59 +00003482 return 0;
3483}
3484
3485/// This function implements the transforms common to both integer remainder
3486/// instructions (urem and srem). It is called by the visitors to those integer
3487/// remainder instructions.
3488/// @brief Common integer remainder transforms
3489Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3490 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3491
3492 if (Instruction *common = commonRemTransforms(I))
3493 return common;
3494
Chris Lattner857e8cd2004-12-12 21:48:58 +00003495 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003496 // X % 0 == undef, we don't need to preserve faults!
3497 if (RHS->equalsInt(0))
3498 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3499
Chris Lattnera2881962003-02-18 19:28:33 +00003500 if (RHS->equalsInt(1)) // X % 1 == 0
3501 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3502
Chris Lattner97943922006-02-28 05:49:21 +00003503 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3504 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3505 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3506 return R;
3507 } else if (isa<PHINode>(Op0I)) {
3508 if (Instruction *NV = FoldOpIntoPhi(I))
3509 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003510 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003511
3512 // See if we can fold away this rem instruction.
3513 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3514 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3515 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3516 KnownZero, KnownOne))
3517 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003518 }
Chris Lattnera2881962003-02-18 19:28:33 +00003519 }
3520
Reid Spencer0a783f72006-11-02 01:53:59 +00003521 return 0;
3522}
3523
3524Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3525 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3526
3527 if (Instruction *common = commonIRemTransforms(I))
3528 return common;
3529
3530 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3531 // X urem C^2 -> X and C
3532 // Check to see if this is an unsigned remainder with an exact power of 2,
3533 // if so, convert to a bitwise and.
3534 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003535 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003536 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003537 }
3538
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003539 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003540 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3541 if (RHSI->getOpcode() == Instruction::Shl &&
3542 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003543 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003544 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003545 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003546 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003547 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003548 }
3549 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003550 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003551
Reid Spencer0a783f72006-11-02 01:53:59 +00003552 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3553 // where C1&C2 are powers of two.
3554 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3555 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3556 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3557 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003558 if ((STO->getValue().isPowerOf2()) &&
3559 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003560 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003561 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003562 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003563 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003564 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003565 }
3566 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003567 }
3568
Chris Lattner3f5b8772002-05-06 16:14:14 +00003569 return 0;
3570}
3571
Reid Spencer0a783f72006-11-02 01:53:59 +00003572Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3573 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3574
Dan Gohmancff55092007-11-05 23:16:33 +00003575 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003576 if (Instruction *common = commonIRemTransforms(I))
3577 return common;
3578
3579 if (Value *RHSNeg = dyn_castNegVal(Op1))
3580 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003581 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003582 // X % -Y -> X % Y
3583 AddUsesToWorkList(I);
3584 I.setOperand(1, RHSNeg);
3585 return &I;
3586 }
3587
Dan Gohmancff55092007-11-05 23:16:33 +00003588 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003589 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003590 if (I.getType()->isInteger()) {
3591 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3592 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3593 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003594 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003595 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003596 }
3597
3598 return 0;
3599}
3600
3601Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003602 return commonRemTransforms(I);
3603}
3604
Chris Lattner8b170942002-08-09 23:47:40 +00003605// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003606static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003607 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003608 if (!isSigned)
3609 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3610 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003611}
3612
3613// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003614static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003615 if (!isSigned)
3616 return C->getValue() == 1; // unsigned
3617
3618 // Calculate 1111111111000000000000
3619 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3620 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003621}
3622
Chris Lattner457dd822004-06-09 07:59:58 +00003623// isOneBitSet - Return true if there is exactly one bit set in the specified
3624// constant.
3625static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003626 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003627}
3628
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003629// isHighOnes - Return true if the constant is of the form 1+0+.
3630// This is the same as lowones(~X).
3631static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003632 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003633}
3634
Reid Spencere4d87aa2006-12-23 06:05:41 +00003635/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003636/// are carefully arranged to allow folding of expressions such as:
3637///
3638/// (A < B) | (A > B) --> (A != B)
3639///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640/// Note that this is only valid if the first and second predicates have the
3641/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003642///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003643/// Three bits are used to represent the condition, as follows:
3644/// 0 A > B
3645/// 1 A == B
3646/// 2 A < B
3647///
3648/// <=> Value Definition
3649/// 000 0 Always false
3650/// 001 1 A > B
3651/// 010 2 A == B
3652/// 011 3 A >= B
3653/// 100 4 A < B
3654/// 101 5 A != B
3655/// 110 6 A <= B
3656/// 111 7 Always true
3657///
3658static unsigned getICmpCode(const ICmpInst *ICI) {
3659 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003660 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 case ICmpInst::ICMP_UGT: return 1; // 001
3662 case ICmpInst::ICMP_SGT: return 1; // 001
3663 case ICmpInst::ICMP_EQ: return 2; // 010
3664 case ICmpInst::ICMP_UGE: return 3; // 011
3665 case ICmpInst::ICMP_SGE: return 3; // 011
3666 case ICmpInst::ICMP_ULT: return 4; // 100
3667 case ICmpInst::ICMP_SLT: return 4; // 100
3668 case ICmpInst::ICMP_NE: return 5; // 101
3669 case ICmpInst::ICMP_ULE: return 6; // 110
3670 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003671 // True -> 7
3672 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003673 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003674 return 0;
3675 }
3676}
3677
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678/// getICmpValue - This is the complement of getICmpCode, which turns an
3679/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003680/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681/// of predicate to use in new icmp instructions.
3682static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3683 switch (code) {
3684 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003685 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003686 case 1:
3687 if (sign)
3688 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3689 else
3690 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3691 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3692 case 3:
3693 if (sign)
3694 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3695 else
3696 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3697 case 4:
3698 if (sign)
3699 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3700 else
3701 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3702 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3703 case 6:
3704 if (sign)
3705 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3706 else
3707 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003708 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003709 }
3710}
3711
Reid Spencere4d87aa2006-12-23 06:05:41 +00003712static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3713 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3714 (ICmpInst::isSignedPredicate(p1) &&
3715 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3716 (ICmpInst::isSignedPredicate(p2) &&
3717 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3718}
3719
3720namespace {
3721// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3722struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003723 InstCombiner &IC;
3724 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725 ICmpInst::Predicate pred;
3726 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3727 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3728 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003729 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3731 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003732 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3733 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003734 return false;
3735 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003736 Instruction *apply(Instruction &Log) const {
3737 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3738 if (ICI->getOperand(0) != LHS) {
3739 assert(ICI->getOperand(1) == LHS);
3740 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003741 }
3742
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003743 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003744 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003745 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003746 unsigned Code;
3747 switch (Log.getOpcode()) {
3748 case Instruction::And: Code = LHSCode & RHSCode; break;
3749 case Instruction::Or: Code = LHSCode | RHSCode; break;
3750 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003751 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003752 }
3753
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003754 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3755 ICmpInst::isSignedPredicate(ICI->getPredicate());
3756
3757 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003758 if (Instruction *I = dyn_cast<Instruction>(RV))
3759 return I;
3760 // Otherwise, it's a constant boolean value...
3761 return IC.ReplaceInstUsesWith(Log, RV);
3762 }
3763};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003764} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003765
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003766// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3767// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003768// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003769Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003770 ConstantInt *OpRHS,
3771 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003772 BinaryOperator &TheAnd) {
3773 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003774 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003775 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003776 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003777
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003778 switch (Op->getOpcode()) {
3779 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003780 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003781 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003782 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003783 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003784 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003785 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003786 }
3787 break;
3788 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003789 if (Together == AndRHS) // (X | C) & C --> C
3790 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003791
Chris Lattner6e7ba452005-01-01 16:22:27 +00003792 if (Op->hasOneUse() && Together != OpRHS) {
3793 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003794 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003795 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003796 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003797 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003798 }
3799 break;
3800 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003801 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003802 // Adding a one to a single bit bit-field should be turned into an XOR
3803 // of the bit. First thing to check is to see if this AND is with a
3804 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003805 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003806
3807 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003808 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003809 // Ok, at this point, we know that we are masking the result of the
3810 // ADD down to exactly one bit. If the constant we are adding has
3811 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003812 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003813
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003814 // Check to see if any bits below the one bit set in AndRHSV are set.
3815 if ((AddRHS & (AndRHSV-1)) == 0) {
3816 // If not, the only thing that can effect the output of the AND is
3817 // the bit specified by AndRHSV. If that bit is set, the effect of
3818 // the XOR is to toggle the bit. If it is clear, then the ADD has
3819 // no effect.
3820 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3821 TheAnd.setOperand(0, X);
3822 return &TheAnd;
3823 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003824 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003825 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003826 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003827 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003828 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003829 }
3830 }
3831 }
3832 }
3833 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003834
3835 case Instruction::Shl: {
3836 // We know that the AND will not produce any of the bits shifted in, so if
3837 // the anded constant includes them, clear them now!
3838 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003839 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003840 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003841 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3842 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003843
Zhou Sheng290bec52007-03-29 08:15:12 +00003844 if (CI->getValue() == ShlMask) {
3845 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003846 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3847 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003848 TheAnd.setOperand(1, CI);
3849 return &TheAnd;
3850 }
3851 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003852 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003853 case Instruction::LShr:
3854 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003855 // 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! This only applies to
3857 // unsigned shifts, because a signed shr may bring in set bits!
3858 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003859 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003860 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003861 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3862 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003863
Zhou Sheng290bec52007-03-29 08:15:12 +00003864 if (CI->getValue() == ShrMask) {
3865 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003866 return ReplaceInstUsesWith(TheAnd, Op);
3867 } else if (CI != AndRHS) {
3868 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3869 return &TheAnd;
3870 }
3871 break;
3872 }
3873 case Instruction::AShr:
3874 // Signed shr.
3875 // See if this is shifting in some sign extension, then masking it out
3876 // with an and.
3877 if (Op->hasOneUse()) {
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 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003882 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003883 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003884 // Make the argument unsigned.
3885 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003886 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003887 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003888 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003889 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003890 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003891 }
3892 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003893 }
3894 return 0;
3895}
3896
Chris Lattner8b170942002-08-09 23:47:40 +00003897
Chris Lattnera96879a2004-09-29 17:40:11 +00003898/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3899/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003900/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3901/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003902/// insert new instructions.
3903Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003904 bool isSigned, bool Inside,
3905 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003906 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003907 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003908 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003909
Chris Lattnera96879a2004-09-29 17:40:11 +00003910 if (Inside) {
3911 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003912 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003913
Reid Spencere4d87aa2006-12-23 06:05:41 +00003914 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003915 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003916 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003917 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3918 return new ICmpInst(pred, V, Hi);
3919 }
3920
3921 // Emit V-Lo <u Hi-Lo
3922 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003923 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003924 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003925 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3926 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003927 }
3928
3929 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003930 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003931
Reid Spencere4e40032007-03-21 23:19:50 +00003932 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003933 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003934 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003935 ICmpInst::Predicate pred = (isSigned ?
3936 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3937 return new ICmpInst(pred, V, Hi);
3938 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003939
Reid Spencere4e40032007-03-21 23:19:50 +00003940 // Emit V-Lo >u Hi-1-Lo
3941 // Note that Hi has already had one subtracted from it, above.
3942 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003943 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003944 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003945 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3946 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003947}
3948
Chris Lattner7203e152005-09-18 07:22:02 +00003949// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3950// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3951// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3952// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003953static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003954 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003955 uint32_t BitWidth = Val->getType()->getBitWidth();
3956 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003957
3958 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003959 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003960 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003961 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003962 return true;
3963}
3964
Chris Lattner7203e152005-09-18 07:22:02 +00003965/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3966/// where isSub determines whether the operator is a sub. If we can fold one of
3967/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003968///
3969/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3970/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3971/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3972///
3973/// return (A +/- B).
3974///
3975Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003976 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003977 Instruction &I) {
3978 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3979 if (!LHSI || LHSI->getNumOperands() != 2 ||
3980 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3981
3982 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3983
3984 switch (LHSI->getOpcode()) {
3985 default: return 0;
3986 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003987 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003988 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003989 if ((Mask->getValue().countLeadingZeros() +
3990 Mask->getValue().countPopulation()) ==
3991 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003992 break;
3993
3994 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3995 // part, we don't need any explicit masks to take them out of A. If that
3996 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003997 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003998 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003999 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004000 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004001 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004002 break;
4003 }
4004 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004005 return 0;
4006 case Instruction::Or:
4007 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004008 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004009 if ((Mask->getValue().countLeadingZeros() +
4010 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004011 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004012 break;
4013 return 0;
4014 }
4015
4016 Instruction *New;
4017 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004018 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004019 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004020 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004021 return InsertNewInstBefore(New, I);
4022}
4023
Chris Lattner7e708292002-06-25 16:13:24 +00004024Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004025 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004026 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004027
Chris Lattnere87597f2004-10-16 18:11:37 +00004028 if (isa<UndefValue>(Op1)) // X & undef -> 0
4029 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4030
Chris Lattner6e7ba452005-01-01 16:22:27 +00004031 // and X, X = X
4032 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004033 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004034
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004035 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004036 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004037 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004038 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4039 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4040 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004041 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004042 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004043 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004044 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004045 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004046 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004047 } else if (isa<ConstantAggregateZero>(Op1)) {
4048 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004049 }
4050 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004051
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004052 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004053 const APInt& AndRHSMask = AndRHS->getValue();
4054 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004055
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004056 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004057 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004058 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004059 Value *Op0LHS = Op0I->getOperand(0);
4060 Value *Op0RHS = Op0I->getOperand(1);
4061 switch (Op0I->getOpcode()) {
4062 case Instruction::Xor:
4063 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004064 // If the mask is only needed on one incoming arm, push it up.
4065 if (Op0I->hasOneUse()) {
4066 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4067 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004068 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004069 Op0RHS->getName()+".masked");
4070 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004071 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004072 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004073 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004074 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004075 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4076 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004077 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004078 Op0LHS->getName()+".masked");
4079 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004080 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004081 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4082 }
4083 }
4084
Chris Lattner6e7ba452005-01-01 16:22:27 +00004085 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004086 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004087 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4088 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4089 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4090 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004091 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004092 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004093 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004094 break;
4095
4096 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004097 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4098 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4099 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4100 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004101 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004102 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004103 }
4104
Chris Lattner58403262003-07-23 19:25:52 +00004105 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004106 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004107 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004108 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004109 // If this is an integer truncation or change from signed-to-unsigned, and
4110 // if the source is an and/or with immediate, transform it. This
4111 // frequently occurs for bitfield accesses.
4112 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004113 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004114 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004115 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004116 if (CastOp->getOpcode() == Instruction::And) {
4117 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004118 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4119 // This will fold the two constants together, which may allow
4120 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004121 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004122 CastOp->getOperand(0), I.getType(),
4123 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004124 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004125 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004126 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004127 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004128 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004129 } else if (CastOp->getOpcode() == Instruction::Or) {
4130 // Change: and (cast (or X, C1) to T), C2
4131 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004132 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004133 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4134 return ReplaceInstUsesWith(I, AndRHS);
4135 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004136 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004137 }
Chris Lattner06782f82003-07-23 19:36:21 +00004138 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004139
4140 // Try to fold constant and into select arguments.
4141 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004142 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004143 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004144 if (isa<PHINode>(Op0))
4145 if (Instruction *NV = FoldOpIntoPhi(I))
4146 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004147 }
4148
Chris Lattner8d969642003-03-10 23:06:50 +00004149 Value *Op0NotVal = dyn_castNotVal(Op0);
4150 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004151
Chris Lattner5b62aa72004-06-18 06:07:51 +00004152 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4153 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4154
Misha Brukmancb6267b2004-07-30 12:50:08 +00004155 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004156 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004157 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004158 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004159 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004160 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004161 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004162
4163 {
Chris Lattner003b6202007-06-15 05:58:24 +00004164 Value *A = 0, *B = 0, *C = 0, *D = 0;
4165 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004166 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4167 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004168
4169 // (A|B) & ~(A&B) -> A^B
4170 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4171 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004172 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004173 }
4174 }
4175
4176 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004177 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4178 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004179
4180 // ~(A&B) & (A|B) -> A^B
4181 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4182 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004183 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004184 }
4185 }
Chris Lattner64daab52006-04-01 08:03:55 +00004186
4187 if (Op0->hasOneUse() &&
4188 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4189 if (A == Op1) { // (A^B)&A -> A&(A^B)
4190 I.swapOperands(); // Simplify below
4191 std::swap(Op0, Op1);
4192 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4193 cast<BinaryOperator>(Op0)->swapOperands();
4194 I.swapOperands(); // Simplify below
4195 std::swap(Op0, Op1);
4196 }
4197 }
4198 if (Op1->hasOneUse() &&
4199 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4200 if (B == Op0) { // B&(A^B) -> B&(B^A)
4201 cast<BinaryOperator>(Op1)->swapOperands();
4202 std::swap(A, B);
4203 }
4204 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004205 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004206 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004207 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004208 }
4209 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004210 }
4211
Reid Spencere4d87aa2006-12-23 06:05:41 +00004212 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4213 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4214 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004215 return R;
4216
Chris Lattner955f3312004-09-28 21:48:02 +00004217 Value *LHSVal, *RHSVal;
4218 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004219 ICmpInst::Predicate LHSCC, RHSCC;
4220 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4221 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4222 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4223 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4224 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4225 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4226 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004227 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4228
4229 // Don't try to fold ICMP_SLT + ICMP_ULT.
4230 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4231 ICmpInst::isSignedPredicate(LHSCC) ==
4232 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004233 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004234 ICmpInst::Predicate GT;
4235 if (ICmpInst::isSignedPredicate(LHSCC) ||
4236 (ICmpInst::isEquality(LHSCC) &&
4237 ICmpInst::isSignedPredicate(RHSCC)))
4238 GT = ICmpInst::ICMP_SGT;
4239 else
4240 GT = ICmpInst::ICMP_UGT;
4241
Reid Spencere4d87aa2006-12-23 06:05:41 +00004242 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4243 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004244 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004245 std::swap(LHS, RHS);
4246 std::swap(LHSCst, RHSCst);
4247 std::swap(LHSCC, RHSCC);
4248 }
4249
Reid Spencere4d87aa2006-12-23 06:05:41 +00004250 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004251 // comparing a value against two constants and and'ing the result
4252 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004253 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4254 // (from the FoldICmpLogical check above), that the two constants
4255 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004256 assert(LHSCst != RHSCst && "Compares not folded above?");
4257
4258 switch (LHSCC) {
4259 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004260 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004261 switch (RHSCC) {
4262 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004263 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4264 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4265 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004266 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004267 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4268 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4269 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004270 return ReplaceInstUsesWith(I, LHS);
4271 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004273 switch (RHSCC) {
4274 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004275 case ICmpInst::ICMP_ULT:
4276 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4277 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4278 break; // (X != 13 & X u< 15) -> no change
4279 case ICmpInst::ICMP_SLT:
4280 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4281 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4282 break; // (X != 13 & X s< 15) -> no change
4283 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4284 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4285 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004286 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004287 case ICmpInst::ICMP_NE:
4288 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004289 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004290 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004291 LHSVal->getName()+".off");
4292 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004293 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4294 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004295 }
4296 break; // (X != 13 & X != 15) -> no change
4297 }
4298 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004299 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004300 switch (RHSCC) {
4301 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004302 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4303 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004304 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004305 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4306 break;
4307 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4308 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004309 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004310 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4311 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004312 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004313 break;
4314 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004315 switch (RHSCC) {
4316 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004317 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4318 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004319 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004320 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4321 break;
4322 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4323 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004324 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004325 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4326 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004327 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004328 break;
4329 case ICmpInst::ICMP_UGT:
4330 switch (RHSCC) {
4331 default: assert(0 && "Unknown integer condition code!");
4332 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4333 return ReplaceInstUsesWith(I, LHS);
4334 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4335 return ReplaceInstUsesWith(I, RHS);
4336 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4337 break;
4338 case ICmpInst::ICMP_NE:
4339 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4340 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4341 break; // (X u> 13 & X != 15) -> no change
4342 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4343 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4344 true, I);
4345 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4346 break;
4347 }
4348 break;
4349 case ICmpInst::ICMP_SGT:
4350 switch (RHSCC) {
4351 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004352 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004353 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4354 return ReplaceInstUsesWith(I, RHS);
4355 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4356 break;
4357 case ICmpInst::ICMP_NE:
4358 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4359 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4360 break; // (X s> 13 & X != 15) -> no change
4361 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4362 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4363 true, I);
4364 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4365 break;
4366 }
4367 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004368 }
4369 }
4370 }
4371
Chris Lattner6fc205f2006-05-05 06:39:07 +00004372 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004373 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4374 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4375 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4376 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004377 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004378 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004379 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4380 I.getType(), TD) &&
4381 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4382 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004383 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004384 Op1C->getOperand(0),
4385 I.getName());
4386 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004387 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004388 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004389 }
Chris Lattnere511b742006-11-14 07:46:50 +00004390
4391 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004392 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4393 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4394 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004395 SI0->getOperand(1) == SI1->getOperand(1) &&
4396 (SI0->hasOneUse() || SI1->hasOneUse())) {
4397 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004398 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004399 SI1->getOperand(0),
4400 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004401 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004402 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004403 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004404 }
4405
Chris Lattner99c65742007-10-24 05:38:08 +00004406 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4407 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4408 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4409 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4410 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4411 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4412 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4413 // If either of the constants are nans, then the whole thing returns
4414 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004415 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004416 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4417 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4418 RHS->getOperand(0));
4419 }
4420 }
4421 }
4422
Chris Lattner7e708292002-06-25 16:13:24 +00004423 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004424}
4425
Chris Lattnerafe91a52006-06-15 19:07:26 +00004426/// CollectBSwapParts - Look to see if the specified value defines a single byte
4427/// in the result. If it does, and if the specified byte hasn't been filled in
4428/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004429static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004430 Instruction *I = dyn_cast<Instruction>(V);
4431 if (I == 0) return true;
4432
4433 // If this is an or instruction, it is an inner node of the bswap.
4434 if (I->getOpcode() == Instruction::Or)
4435 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4436 CollectBSwapParts(I->getOperand(1), ByteValues);
4437
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004438 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004439 // If this is a shift by a constant int, and it is "24", then its operand
4440 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004441 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004442 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004443 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004444 8*(ByteValues.size()-1))
4445 return true;
4446
4447 unsigned DestNo;
4448 if (I->getOpcode() == Instruction::Shl) {
4449 // X << 24 defines the top byte with the lowest of the input bytes.
4450 DestNo = ByteValues.size()-1;
4451 } else {
4452 // X >>u 24 defines the low byte with the highest of the input bytes.
4453 DestNo = 0;
4454 }
4455
4456 // If the destination byte value is already defined, the values are or'd
4457 // together, which isn't a bswap (unless it's an or of the same bits).
4458 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4459 return true;
4460 ByteValues[DestNo] = I->getOperand(0);
4461 return false;
4462 }
4463
4464 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4465 // don't have this.
4466 Value *Shift = 0, *ShiftLHS = 0;
4467 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4468 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4469 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4470 return true;
4471 Instruction *SI = cast<Instruction>(Shift);
4472
4473 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004474 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4475 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004476 return true;
4477
4478 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4479 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004480 if (AndAmt->getValue().getActiveBits() > 64)
4481 return true;
4482 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004483 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004484 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004485 break;
4486 // Unknown mask for bswap.
4487 if (DestByte == ByteValues.size()) return true;
4488
Reid Spencerb83eb642006-10-20 07:07:24 +00004489 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004490 unsigned SrcByte;
4491 if (SI->getOpcode() == Instruction::Shl)
4492 SrcByte = DestByte - ShiftBytes;
4493 else
4494 SrcByte = DestByte + ShiftBytes;
4495
4496 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4497 if (SrcByte != ByteValues.size()-DestByte-1)
4498 return true;
4499
4500 // If the destination byte value is already defined, the values are or'd
4501 // together, which isn't a bswap (unless it's an or of the same bits).
4502 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4503 return true;
4504 ByteValues[DestByte] = SI->getOperand(0);
4505 return false;
4506}
4507
4508/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4509/// If so, insert the new bswap intrinsic and return it.
4510Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004511 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4512 if (!ITy || ITy->getBitWidth() % 16)
4513 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004514
4515 /// ByteValues - For each byte of the result, we keep track of which value
4516 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004517 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004518 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004519
4520 // Try to find all the pieces corresponding to the bswap.
4521 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4522 CollectBSwapParts(I.getOperand(1), ByteValues))
4523 return 0;
4524
4525 // Check to see if all of the bytes come from the same value.
4526 Value *V = ByteValues[0];
4527 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4528
4529 // Check to make sure that all of the bytes come from the same value.
4530 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4531 if (ByteValues[i] != V)
4532 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004533 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004534 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004535 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004536 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004537}
4538
4539
Chris Lattner7e708292002-06-25 16:13:24 +00004540Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004541 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004542 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004543
Chris Lattner42593e62007-03-24 23:56:43 +00004544 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004545 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004546
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004547 // or X, X = X
4548 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004549 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004550
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004551 // See if we can simplify any instructions used by the instruction whose sole
4552 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004553 if (!isa<VectorType>(I.getType())) {
4554 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4555 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4556 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4557 KnownZero, KnownOne))
4558 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004559 } else if (isa<ConstantAggregateZero>(Op1)) {
4560 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4561 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4562 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4563 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004564 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004565
4566
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004567
Chris Lattner3f5b8772002-05-06 16:14:14 +00004568 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004569 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004570 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004571 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4572 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004573 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004574 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004575 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004576 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004577 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004578 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004579
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004580 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4581 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004582 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004583 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004584 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004585 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004586 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004587 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004588
4589 // Try to fold constant and into select arguments.
4590 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004591 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004592 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004593 if (isa<PHINode>(Op0))
4594 if (Instruction *NV = FoldOpIntoPhi(I))
4595 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004596 }
4597
Chris Lattner4f637d42006-01-06 17:59:59 +00004598 Value *A = 0, *B = 0;
4599 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004600
4601 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4602 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4603 return ReplaceInstUsesWith(I, Op1);
4604 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4605 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4606 return ReplaceInstUsesWith(I, Op0);
4607
Chris Lattner6423d4c2006-07-10 20:25:24 +00004608 // (A | B) | C and A | (B | C) -> bswap if possible.
4609 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004610 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004611 match(Op1, m_Or(m_Value(), m_Value())) ||
4612 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4613 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004614 if (Instruction *BSwap = MatchBSwap(I))
4615 return BSwap;
4616 }
4617
Chris Lattner6e4c6492005-05-09 04:58:36 +00004618 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4619 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004620 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004621 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004622 InsertNewInstBefore(NOr, I);
4623 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004624 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004625 }
4626
4627 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4628 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004629 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004630 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004631 InsertNewInstBefore(NOr, I);
4632 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004633 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004634 }
4635
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004636 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004637 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004638 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4639 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004640 Value *V1 = 0, *V2 = 0, *V3 = 0;
4641 C1 = dyn_cast<ConstantInt>(C);
4642 C2 = dyn_cast<ConstantInt>(D);
4643 if (C1 && C2) { // (A & C1)|(B & C2)
4644 // If we have: ((V + N) & C1) | (V & C2)
4645 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4646 // replace with V+N.
4647 if (C1->getValue() == ~C2->getValue()) {
4648 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4649 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4650 // Add commutes, try both ways.
4651 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4652 return ReplaceInstUsesWith(I, A);
4653 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4654 return ReplaceInstUsesWith(I, A);
4655 }
4656 // Or commutes, try both ways.
4657 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4658 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4659 // Add commutes, try both ways.
4660 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4661 return ReplaceInstUsesWith(I, B);
4662 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4663 return ReplaceInstUsesWith(I, B);
4664 }
4665 }
Chris Lattner044e5332007-04-08 08:01:49 +00004666 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004667 }
4668
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004669 // Check to see if we have any common things being and'ed. If so, find the
4670 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004671 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4672 if (A == B) // (A & C)|(A & D) == A & (C|D)
4673 V1 = A, V2 = C, V3 = D;
4674 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4675 V1 = A, V2 = B, V3 = C;
4676 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4677 V1 = C, V2 = A, V3 = D;
4678 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4679 V1 = C, V2 = A, V3 = B;
4680
4681 if (V1) {
4682 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004683 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4684 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004685 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004686 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004687 }
Chris Lattnere511b742006-11-14 07:46:50 +00004688
4689 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004690 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4691 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4692 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004693 SI0->getOperand(1) == SI1->getOperand(1) &&
4694 (SI0->hasOneUse() || SI1->hasOneUse())) {
4695 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004696 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004697 SI1->getOperand(0),
4698 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004699 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004700 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004701 }
4702 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004703
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004704 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4705 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004706 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004707 } else {
4708 A = 0;
4709 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004710 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004711 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4712 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004713 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004714
Misha Brukmancb6267b2004-07-30 12:50:08 +00004715 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004716 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004717 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004718 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004720 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004721 }
Chris Lattnera2881962003-02-18 19:28:33 +00004722
Reid Spencere4d87aa2006-12-23 06:05:41 +00004723 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4724 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4725 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004726 return R;
4727
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004728 Value *LHSVal, *RHSVal;
4729 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004730 ICmpInst::Predicate LHSCC, RHSCC;
4731 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4732 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4733 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4734 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4735 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4736 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4737 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004738 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4739 // We can't fold (ugt x, C) | (sgt x, C2).
4740 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004741 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004742 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004743 bool NeedsSwap;
4744 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004745 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004746 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004747 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004748
4749 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004750 std::swap(LHS, RHS);
4751 std::swap(LHSCst, RHSCst);
4752 std::swap(LHSCC, RHSCC);
4753 }
4754
Reid Spencere4d87aa2006-12-23 06:05:41 +00004755 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004756 // comparing a value against two constants and or'ing the result
4757 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004758 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4759 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004760 // equal.
4761 assert(LHSCst != RHSCst && "Compares not folded above?");
4762
4763 switch (LHSCC) {
4764 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004765 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004766 switch (RHSCC) {
4767 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004768 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004769 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4770 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004771 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004772 LHSVal->getName()+".off");
4773 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004774 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004775 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004776 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004777 break; // (X == 13 | X == 15) -> no change
4778 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4779 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004780 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004781 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4782 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4783 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004784 return ReplaceInstUsesWith(I, RHS);
4785 }
4786 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004787 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004788 switch (RHSCC) {
4789 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004790 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4791 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4792 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004793 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004794 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4795 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4796 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004797 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004798 }
4799 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004800 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004801 switch (RHSCC) {
4802 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004803 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004804 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004805 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004806 // If RHSCst is [us]MAXINT, it is always false. Not handling
4807 // this can cause overflow.
4808 if (RHSCst->isMaxValue(false))
4809 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004810 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4811 false, I);
4812 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4813 break;
4814 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4815 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004816 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004817 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4818 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004819 }
4820 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004821 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004822 switch (RHSCC) {
4823 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004824 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4825 break;
4826 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004827 // If RHSCst is [us]MAXINT, it is always false. Not handling
4828 // this can cause overflow.
4829 if (RHSCst->isMaxValue(true))
4830 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004831 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4832 false, I);
4833 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4834 break;
4835 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4836 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4837 return ReplaceInstUsesWith(I, RHS);
4838 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4839 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004840 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004841 break;
4842 case ICmpInst::ICMP_UGT:
4843 switch (RHSCC) {
4844 default: assert(0 && "Unknown integer condition code!");
4845 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4846 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4847 return ReplaceInstUsesWith(I, LHS);
4848 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4849 break;
4850 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4851 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004852 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004853 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4854 break;
4855 }
4856 break;
4857 case ICmpInst::ICMP_SGT:
4858 switch (RHSCC) {
4859 default: assert(0 && "Unknown integer condition code!");
4860 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4861 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4862 return ReplaceInstUsesWith(I, LHS);
4863 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4864 break;
4865 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4866 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004867 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004868 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4869 break;
4870 }
4871 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004872 }
4873 }
4874 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004875
4876 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004877 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004878 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004879 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004880 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4881 !isa<ICmpInst>(Op1C->getOperand(0))) {
4882 const Type *SrcTy = Op0C->getOperand(0)->getType();
4883 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4884 // Only do this if the casts both really cause code to be
4885 // generated.
4886 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4887 I.getType(), TD) &&
4888 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4889 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004890 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004891 Op1C->getOperand(0),
4892 I.getName());
4893 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004894 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004895 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004896 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004897 }
Chris Lattner99c65742007-10-24 05:38:08 +00004898 }
4899
4900
4901 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4902 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4903 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4904 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004905 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4906 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004907 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4908 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4909 // If either of the constants are nans, then the whole thing returns
4910 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004911 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004912 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4913
4914 // Otherwise, no need to compare the two constants, compare the
4915 // rest.
4916 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4917 RHS->getOperand(0));
4918 }
4919 }
4920 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004921
Chris Lattner7e708292002-06-25 16:13:24 +00004922 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004923}
4924
Dan Gohman844731a2008-05-13 00:00:25 +00004925namespace {
4926
Chris Lattnerc317d392004-02-16 01:20:27 +00004927// XorSelf - Implements: X ^ X --> 0
4928struct XorSelf {
4929 Value *RHS;
4930 XorSelf(Value *rhs) : RHS(rhs) {}
4931 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4932 Instruction *apply(BinaryOperator &Xor) const {
4933 return &Xor;
4934 }
4935};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004936
Dan Gohman844731a2008-05-13 00:00:25 +00004937}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004938
Chris Lattner7e708292002-06-25 16:13:24 +00004939Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004940 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004942
Evan Chengd34af782008-03-25 20:07:13 +00004943 if (isa<UndefValue>(Op1)) {
4944 if (isa<UndefValue>(Op0))
4945 // Handle undef ^ undef -> 0 special case. This is a common
4946 // idiom (misuse).
4947 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004948 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004949 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004950
Chris Lattnerc317d392004-02-16 01:20:27 +00004951 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4952 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004953 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004955 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004956
4957 // See if we can simplify any instructions used by the instruction whose sole
4958 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004959 if (!isa<VectorType>(I.getType())) {
4960 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4961 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4962 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4963 KnownZero, KnownOne))
4964 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004965 } else if (isa<ConstantAggregateZero>(Op1)) {
4966 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004967 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004968
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004969 // Is this a ~ operation?
4970 if (Value *NotOp = dyn_castNotVal(&I)) {
4971 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4972 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4973 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4974 if (Op0I->getOpcode() == Instruction::And ||
4975 Op0I->getOpcode() == Instruction::Or) {
4976 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4977 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4978 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004979 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004980 Op0I->getOperand(1)->getName()+".not");
4981 InsertNewInstBefore(NotY, I);
4982 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004983 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004984 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004985 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004986 }
4987 }
4988 }
4989 }
4990
4991
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004992 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004993 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4994 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4995 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004996 return new ICmpInst(ICI->getInversePredicate(),
4997 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004998
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004999 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5000 return new FCmpInst(FCI->getInversePredicate(),
5001 FCI->getOperand(0), FCI->getOperand(1));
5002 }
5003
Reid Spencere4d87aa2006-12-23 06:05:41 +00005004 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005005 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005006 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5007 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005008 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5009 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005010 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005011 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005012 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005013
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005014 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005015 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005016 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005017 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005018 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005019 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005020 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005021 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005022 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005023 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005024 // (X + C) ^ signbit -> (X + C + signbit)
5025 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005026 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005027
Chris Lattner7c4049c2004-01-12 19:35:11 +00005028 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005029 } else if (Op0I->getOpcode() == Instruction::Or) {
5030 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005031 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005032 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5033 // Anything in both C1 and C2 is known to be zero, remove it from
5034 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005035 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005036 NewRHS = ConstantExpr::getAnd(NewRHS,
5037 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005038 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005039 I.setOperand(0, Op0I->getOperand(0));
5040 I.setOperand(1, NewRHS);
5041 return &I;
5042 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005043 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005044 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005045 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005046
5047 // Try to fold constant and into select arguments.
5048 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005049 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005050 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005051 if (isa<PHINode>(Op0))
5052 if (Instruction *NV = FoldOpIntoPhi(I))
5053 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005054 }
5055
Chris Lattner8d969642003-03-10 23:06:50 +00005056 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005057 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005058 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005059
Chris Lattner8d969642003-03-10 23:06:50 +00005060 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005061 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005062 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005063
Chris Lattner318bf792007-03-18 22:51:34 +00005064
5065 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5066 if (Op1I) {
5067 Value *A, *B;
5068 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5069 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005070 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005071 I.swapOperands();
5072 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005073 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005074 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005075 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005076 }
Chris Lattner318bf792007-03-18 22:51:34 +00005077 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5078 if (Op0 == A) // A^(A^B) == B
5079 return ReplaceInstUsesWith(I, B);
5080 else if (Op0 == B) // A^(B^A) == B
5081 return ReplaceInstUsesWith(I, A);
5082 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005083 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005084 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005085 std::swap(A, B);
5086 }
Chris Lattner318bf792007-03-18 22:51:34 +00005087 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005088 I.swapOperands(); // Simplified below.
5089 std::swap(Op0, Op1);
5090 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005091 }
Chris Lattner318bf792007-03-18 22:51:34 +00005092 }
5093
5094 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5095 if (Op0I) {
5096 Value *A, *B;
5097 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5098 if (A == Op1) // (B|A)^B == (A|B)^B
5099 std::swap(A, B);
5100 if (B == Op1) { // (A|B)^B == A & ~B
5101 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005102 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5103 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005104 }
Chris Lattner318bf792007-03-18 22:51:34 +00005105 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5106 if (Op1 == A) // (A^B)^A == B
5107 return ReplaceInstUsesWith(I, B);
5108 else if (Op1 == B) // (B^A)^A == B
5109 return ReplaceInstUsesWith(I, A);
5110 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5111 if (A == Op1) // (A&B)^A -> (B&A)^A
5112 std::swap(A, B);
5113 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005114 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005115 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005116 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5117 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005118 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005119 }
Chris Lattner318bf792007-03-18 22:51:34 +00005120 }
5121
5122 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5123 if (Op0I && Op1I && Op0I->isShift() &&
5124 Op0I->getOpcode() == Op1I->getOpcode() &&
5125 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5126 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5127 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005128 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005129 Op1I->getOperand(0),
5130 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005131 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005132 Op1I->getOperand(1));
5133 }
5134
5135 if (Op0I && Op1I) {
5136 Value *A, *B, *C, *D;
5137 // (A & B)^(A | B) -> A ^ B
5138 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5139 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5140 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005141 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005142 }
5143 // (A | B)^(A & B) -> A ^ B
5144 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5145 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5146 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005147 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005148 }
5149
5150 // (A & B)^(C & D)
5151 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5152 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5153 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5154 // (X & Y)^(X & Y) -> (Y^Z) & X
5155 Value *X = 0, *Y = 0, *Z = 0;
5156 if (A == C)
5157 X = A, Y = B, Z = D;
5158 else if (A == D)
5159 X = A, Y = B, Z = C;
5160 else if (B == C)
5161 X = B, Y = A, Z = D;
5162 else if (B == D)
5163 X = B, Y = A, Z = C;
5164
5165 if (X) {
5166 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005167 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5168 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005169 }
5170 }
5171 }
5172
Reid Spencere4d87aa2006-12-23 06:05:41 +00005173 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5174 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5175 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005176 return R;
5177
Chris Lattner6fc205f2006-05-05 06:39:07 +00005178 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005179 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005180 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005181 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5182 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005183 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005184 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005185 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5186 I.getType(), TD) &&
5187 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5188 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005189 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005190 Op1C->getOperand(0),
5191 I.getName());
5192 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005193 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005194 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005195 }
Chris Lattner99c65742007-10-24 05:38:08 +00005196 }
Chris Lattner7e708292002-06-25 16:13:24 +00005197 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005198}
5199
Chris Lattnera96879a2004-09-29 17:40:11 +00005200/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5201/// overflowed for this type.
5202static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005203 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005204 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005205
Reid Spencere4e40032007-03-21 23:19:50 +00005206 if (IsSigned)
5207 if (In2->getValue().isNegative())
5208 return Result->getValue().sgt(In1->getValue());
5209 else
5210 return Result->getValue().slt(In1->getValue());
5211 else
5212 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005213}
5214
Chris Lattner574da9b2005-01-13 20:14:25 +00005215/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5216/// code necessary to compute the offset from the base pointer (without adding
5217/// in the base pointer). Return the result as a signed integer of intptr size.
5218static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5219 TargetData &TD = IC.getTargetData();
5220 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005221 const Type *IntPtrTy = TD.getIntPtrType();
5222 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005223
5224 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005225 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005226 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005227
Chris Lattner574da9b2005-01-13 20:14:25 +00005228 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5229 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005230 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005231 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5232 if (OpC->isZero()) continue;
5233
5234 // Handle a struct index, which adds its field offset to the pointer.
5235 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5236 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5237
5238 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5239 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005240 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005241 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005242 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005243 ConstantInt::get(IntPtrTy, Size),
5244 GEP->getName()+".offs"), I);
5245 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005246 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005247
5248 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5249 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5250 Scale = ConstantExpr::getMul(OC, Scale);
5251 if (Constant *RC = dyn_cast<Constant>(Result))
5252 Result = ConstantExpr::getAdd(RC, Scale);
5253 else {
5254 // Emit an add instruction.
5255 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005256 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005257 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005258 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005259 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005260 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005261 // Convert to correct type.
5262 if (Op->getType() != IntPtrTy) {
5263 if (Constant *OpC = dyn_cast<Constant>(Op))
5264 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5265 else
5266 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5267 Op->getName()+".c"), I);
5268 }
5269 if (Size != 1) {
5270 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5271 if (Constant *OpC = dyn_cast<Constant>(Op))
5272 Op = ConstantExpr::getMul(OpC, Scale);
5273 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005274 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005275 GEP->getName()+".idx"), I);
5276 }
5277
5278 // Emit an add instruction.
5279 if (isa<Constant>(Op) && isa<Constant>(Result))
5280 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5281 cast<Constant>(Result));
5282 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005283 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005284 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005285 }
5286 return Result;
5287}
5288
Chris Lattner10c0d912008-04-22 02:53:33 +00005289
5290/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5291/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5292/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5293/// complex, and scales are involved. The above expression would also be legal
5294/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5295/// later form is less amenable to optimization though, and we are allowed to
5296/// generate the first by knowing that pointer arithmetic doesn't overflow.
5297///
5298/// If we can't emit an optimized form for this expression, this returns null.
5299///
5300static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5301 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005302 TargetData &TD = IC.getTargetData();
5303 gep_type_iterator GTI = gep_type_begin(GEP);
5304
5305 // Check to see if this gep only has a single variable index. If so, and if
5306 // any constant indices are a multiple of its scale, then we can compute this
5307 // in terms of the scale of the variable index. For example, if the GEP
5308 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5309 // because the expression will cross zero at the same point.
5310 unsigned i, e = GEP->getNumOperands();
5311 int64_t Offset = 0;
5312 for (i = 1; i != e; ++i, ++GTI) {
5313 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5314 // Compute the aggregate offset of constant indices.
5315 if (CI->isZero()) continue;
5316
5317 // Handle a struct index, which adds its field offset to the pointer.
5318 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5319 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5320 } else {
5321 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5322 Offset += Size*CI->getSExtValue();
5323 }
5324 } else {
5325 // Found our variable index.
5326 break;
5327 }
5328 }
5329
5330 // If there are no variable indices, we must have a constant offset, just
5331 // evaluate it the general way.
5332 if (i == e) return 0;
5333
5334 Value *VariableIdx = GEP->getOperand(i);
5335 // Determine the scale factor of the variable element. For example, this is
5336 // 4 if the variable index is into an array of i32.
5337 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5338
5339 // Verify that there are no other variable indices. If so, emit the hard way.
5340 for (++i, ++GTI; i != e; ++i, ++GTI) {
5341 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5342 if (!CI) return 0;
5343
5344 // Compute the aggregate offset of constant indices.
5345 if (CI->isZero()) continue;
5346
5347 // Handle a struct index, which adds its field offset to the pointer.
5348 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5349 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5350 } else {
5351 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5352 Offset += Size*CI->getSExtValue();
5353 }
5354 }
5355
5356 // Okay, we know we have a single variable index, which must be a
5357 // pointer/array/vector index. If there is no offset, life is simple, return
5358 // the index.
5359 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5360 if (Offset == 0) {
5361 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5362 // we don't need to bother extending: the extension won't affect where the
5363 // computation crosses zero.
5364 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5365 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5366 VariableIdx->getNameStart(), &I);
5367 return VariableIdx;
5368 }
5369
5370 // Otherwise, there is an index. The computation we will do will be modulo
5371 // the pointer size, so get it.
5372 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5373
5374 Offset &= PtrSizeMask;
5375 VariableScale &= PtrSizeMask;
5376
5377 // To do this transformation, any constant index must be a multiple of the
5378 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5379 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5380 // multiple of the variable scale.
5381 int64_t NewOffs = Offset / (int64_t)VariableScale;
5382 if (Offset != NewOffs*(int64_t)VariableScale)
5383 return 0;
5384
5385 // Okay, we can do this evaluation. Start by converting the index to intptr.
5386 const Type *IntPtrTy = TD.getIntPtrType();
5387 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005388 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005389 true /*SExt*/,
5390 VariableIdx->getNameStart(), &I);
5391 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005392 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005393}
5394
5395
Reid Spencere4d87aa2006-12-23 06:05:41 +00005396/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005397/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005398Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5399 ICmpInst::Predicate Cond,
5400 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005401 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005402
Chris Lattner10c0d912008-04-22 02:53:33 +00005403 // Look through bitcasts.
5404 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5405 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005406
Chris Lattner574da9b2005-01-13 20:14:25 +00005407 Value *PtrBase = GEPLHS->getOperand(0);
5408 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005409 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005410 // This transformation (ignoring the base and scales) is valid because we
5411 // know pointers can't overflow. See if we can output an optimized form.
5412 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5413
5414 // If not, synthesize the offset the hard way.
5415 if (Offset == 0)
5416 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005417 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5418 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005419 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005420 // If the base pointers are different, but the indices are the same, just
5421 // compare the base pointer.
5422 if (PtrBase != GEPRHS->getOperand(0)) {
5423 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005424 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005425 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005426 if (IndicesTheSame)
5427 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5428 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5429 IndicesTheSame = false;
5430 break;
5431 }
5432
5433 // If all indices are the same, just compare the base pointers.
5434 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005435 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5436 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005437
5438 // Otherwise, the base pointers are different and the indices are
5439 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005440 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005441 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005442
Chris Lattnere9d782b2005-01-13 22:25:21 +00005443 // If one of the GEPs has all zero indices, recurse.
5444 bool AllZeros = true;
5445 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5446 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5447 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5448 AllZeros = false;
5449 break;
5450 }
5451 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005452 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5453 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005454
5455 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005456 AllZeros = true;
5457 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5458 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5459 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5460 AllZeros = false;
5461 break;
5462 }
5463 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005464 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005465
Chris Lattner4401c9c2005-01-14 00:20:05 +00005466 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5467 // If the GEPs only differ by one index, compare it.
5468 unsigned NumDifferences = 0; // Keep track of # differences.
5469 unsigned DiffOperand = 0; // The operand that differs.
5470 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5471 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005472 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5473 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005474 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005475 NumDifferences = 2;
5476 break;
5477 } else {
5478 if (NumDifferences++) break;
5479 DiffOperand = i;
5480 }
5481 }
5482
5483 if (NumDifferences == 0) // SAME GEP?
5484 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005485 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005486 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005487
Chris Lattner4401c9c2005-01-14 00:20:05 +00005488 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005489 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5490 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005491 // Make sure we do a signed comparison here.
5492 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005493 }
5494 }
5495
Reid Spencere4d87aa2006-12-23 06:05:41 +00005496 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005497 // the result to fold to a constant!
5498 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5499 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5500 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5501 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5502 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005503 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005504 }
5505 }
5506 return 0;
5507}
5508
Chris Lattnera5406232008-05-19 20:18:56 +00005509/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5510///
5511Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5512 Instruction *LHSI,
5513 Constant *RHSC) {
5514 if (!isa<ConstantFP>(RHSC)) return 0;
5515 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5516
5517 // Get the width of the mantissa. We don't want to hack on conversions that
5518 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005519 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005520 if (MantissaWidth == -1) return 0; // Unknown.
5521
5522 // Check to see that the input is converted from an integer type that is small
5523 // enough that preserves all bits. TODO: check here for "known" sign bits.
5524 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5525 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5526
5527 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5528 if (isa<UIToFPInst>(LHSI))
5529 ++InputSize;
5530
5531 // If the conversion would lose info, don't hack on this.
5532 if ((int)InputSize > MantissaWidth)
5533 return 0;
5534
5535 // Otherwise, we can potentially simplify the comparison. We know that it
5536 // will always come through as an integer value and we know the constant is
5537 // not a NAN (it would have been previously simplified).
5538 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5539
5540 ICmpInst::Predicate Pred;
5541 switch (I.getPredicate()) {
5542 default: assert(0 && "Unexpected predicate!");
5543 case FCmpInst::FCMP_UEQ:
5544 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5545 case FCmpInst::FCMP_UGT:
5546 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5547 case FCmpInst::FCMP_UGE:
5548 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5549 case FCmpInst::FCMP_ULT:
5550 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5551 case FCmpInst::FCMP_ULE:
5552 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5553 case FCmpInst::FCMP_UNE:
5554 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5555 case FCmpInst::FCMP_ORD:
5556 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5557 case FCmpInst::FCMP_UNO:
5558 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5559 }
5560
5561 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5562
5563 // Now we know that the APFloat is a normal number, zero or inf.
5564
Chris Lattner85162782008-05-20 03:50:52 +00005565 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005566 // comparing an i8 to 300.0.
5567 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5568
5569 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5570 // and large values.
5571 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5572 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5573 APFloat::rmNearestTiesToEven);
5574 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5575 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5576 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5577 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5578 }
5579
5580 // See if the RHS value is < SignedMin.
5581 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5582 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5583 APFloat::rmNearestTiesToEven);
5584 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5585 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5586 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5587 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5588 }
5589
5590 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5591 // it may still be fractional. See if it is fractional by casting the FP
5592 // value to the integer value and back, checking for equality. Don't do this
5593 // for zero, because -0.0 is not fractional.
5594 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5595 if (!RHS.isZero() &&
5596 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5597 // If we had a comparison against a fractional value, we have to adjust
5598 // the compare predicate and sometimes the value. RHSC is rounded towards
5599 // zero at this point.
5600 switch (Pred) {
5601 default: assert(0 && "Unexpected integer comparison!");
5602 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5603 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5604 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5605 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5606 case ICmpInst::ICMP_SLE:
5607 // (float)int <= 4.4 --> int <= 4
5608 // (float)int <= -4.4 --> int < -4
5609 if (RHS.isNegative())
5610 Pred = ICmpInst::ICMP_SLT;
5611 break;
5612 case ICmpInst::ICMP_SLT:
5613 // (float)int < -4.4 --> int < -4
5614 // (float)int < 4.4 --> int <= 4
5615 if (!RHS.isNegative())
5616 Pred = ICmpInst::ICMP_SLE;
5617 break;
5618 case ICmpInst::ICMP_SGT:
5619 // (float)int > 4.4 --> int > 4
5620 // (float)int > -4.4 --> int >= -4
5621 if (RHS.isNegative())
5622 Pred = ICmpInst::ICMP_SGE;
5623 break;
5624 case ICmpInst::ICMP_SGE:
5625 // (float)int >= -4.4 --> int >= -4
5626 // (float)int >= 4.4 --> int > 4
5627 if (!RHS.isNegative())
5628 Pred = ICmpInst::ICMP_SGT;
5629 break;
5630 }
5631 }
5632
5633 // Lower this FP comparison into an appropriate integer version of the
5634 // comparison.
5635 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5636}
5637
Reid Spencere4d87aa2006-12-23 06:05:41 +00005638Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5639 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005640 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005641
Chris Lattner58e97462007-01-14 19:42:17 +00005642 // Fold trivial predicates.
5643 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5644 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5645 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5646 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5647
5648 // Simplify 'fcmp pred X, X'
5649 if (Op0 == Op1) {
5650 switch (I.getPredicate()) {
5651 default: assert(0 && "Unknown predicate!");
5652 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5653 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5654 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5655 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5656 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5657 case FCmpInst::FCMP_OLT: // True if ordered and less than
5658 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5659 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5660
5661 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5662 case FCmpInst::FCMP_ULT: // True if unordered or less than
5663 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5664 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5665 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5666 I.setPredicate(FCmpInst::FCMP_UNO);
5667 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5668 return &I;
5669
5670 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5671 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5672 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5673 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5674 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5675 I.setPredicate(FCmpInst::FCMP_ORD);
5676 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5677 return &I;
5678 }
5679 }
5680
Reid Spencere4d87aa2006-12-23 06:05:41 +00005681 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005682 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005683
Reid Spencere4d87aa2006-12-23 06:05:41 +00005684 // Handle fcmp with constant RHS
5685 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005686 // If the constant is a nan, see if we can fold the comparison based on it.
5687 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5688 if (CFP->getValueAPF().isNaN()) {
5689 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5690 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005691 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5692 "Comparison must be either ordered or unordered!");
5693 // True if unordered.
5694 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005695 }
5696 }
5697
Reid Spencere4d87aa2006-12-23 06:05:41 +00005698 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5699 switch (LHSI->getOpcode()) {
5700 case Instruction::PHI:
5701 if (Instruction *NV = FoldOpIntoPhi(I))
5702 return NV;
5703 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005704 case Instruction::SIToFP:
5705 case Instruction::UIToFP:
5706 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5707 return NV;
5708 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005709 case Instruction::Select:
5710 // If either operand of the select is a constant, we can fold the
5711 // comparison into the select arms, which will cause one to be
5712 // constant folded and the select turned into a bitwise or.
5713 Value *Op1 = 0, *Op2 = 0;
5714 if (LHSI->hasOneUse()) {
5715 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5716 // Fold the known value into the constant operand.
5717 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5718 // Insert a new FCmp of the other select operand.
5719 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5720 LHSI->getOperand(2), RHSC,
5721 I.getName()), I);
5722 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5723 // Fold the known value into the constant operand.
5724 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5725 // Insert a new FCmp of the other select operand.
5726 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5727 LHSI->getOperand(1), RHSC,
5728 I.getName()), I);
5729 }
5730 }
5731
5732 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005733 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005734 break;
5735 }
5736 }
5737
5738 return Changed ? &I : 0;
5739}
5740
5741Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5742 bool Changed = SimplifyCompare(I);
5743 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5744 const Type *Ty = Op0->getType();
5745
5746 // icmp X, X
5747 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005748 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005749 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005750
5751 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005752 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005753
Reid Spencere4d87aa2006-12-23 06:05:41 +00005754 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005755 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005756 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5757 isa<ConstantPointerNull>(Op0)) &&
5758 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005759 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005760 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005761 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005762
Reid Spencere4d87aa2006-12-23 06:05:41 +00005763 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005764 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005765 switch (I.getPredicate()) {
5766 default: assert(0 && "Invalid icmp instruction!");
5767 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005768 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005769 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005770 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005771 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005772 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005773 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005774
Reid Spencere4d87aa2006-12-23 06:05:41 +00005775 case ICmpInst::ICMP_UGT:
5776 case ICmpInst::ICMP_SGT:
5777 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005778 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005779 case ICmpInst::ICMP_ULT:
5780 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005781 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005782 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005783 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005784 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005785 case ICmpInst::ICMP_UGE:
5786 case ICmpInst::ICMP_SGE:
5787 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005788 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005789 case ICmpInst::ICMP_ULE:
5790 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005791 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005792 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005793 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005794 }
5795 }
Chris Lattner8b170942002-08-09 23:47:40 +00005796 }
5797
Chris Lattner2be51ae2004-06-09 04:24:29 +00005798 // See if we are doing a comparison between a constant and an instruction that
5799 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005800 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005801 Value *A, *B;
5802
Chris Lattnerb6566012008-01-05 01:18:20 +00005803 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5804 if (I.isEquality() && CI->isNullValue() &&
5805 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5806 // (icmp cond A B) if cond is equality
5807 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005808 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005809
Reid Spencere4d87aa2006-12-23 06:05:41 +00005810 switch (I.getPredicate()) {
5811 default: break;
5812 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5813 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005814 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005815 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5816 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5817 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5818 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005819 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5820 if (CI->isMinValue(true))
5821 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5822 ConstantInt::getAllOnesValue(Op0->getType()));
5823
Reid Spencere4d87aa2006-12-23 06:05:41 +00005824 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005825
Reid Spencere4d87aa2006-12-23 06:05:41 +00005826 case ICmpInst::ICMP_SLT:
5827 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005828 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005829 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5830 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5831 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5832 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5833 break;
5834
5835 case ICmpInst::ICMP_UGT:
5836 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005837 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005838 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5839 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5840 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5841 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005842
5843 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5844 if (CI->isMaxValue(true))
5845 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5846 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005847 break;
5848
5849 case ICmpInst::ICMP_SGT:
5850 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005852 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5853 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5854 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5855 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5856 break;
5857
5858 case ICmpInst::ICMP_ULE:
5859 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005860 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005861 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5862 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5863 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5864 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5865 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005866
Reid Spencere4d87aa2006-12-23 06:05:41 +00005867 case ICmpInst::ICMP_SLE:
5868 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005869 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005870 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5871 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5872 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5873 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5874 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005875
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876 case ICmpInst::ICMP_UGE:
5877 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005878 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005879 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5880 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5881 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5882 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5883 break;
5884
5885 case ICmpInst::ICMP_SGE:
5886 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5889 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5890 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5891 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5892 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005893 }
5894
Reid Spencere4d87aa2006-12-23 06:05:41 +00005895 // If we still have a icmp le or icmp ge instruction, turn it into the
5896 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005897 // already been handled above, this requires little checking.
5898 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005899 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005900 default: break;
5901 case ICmpInst::ICMP_ULE:
5902 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5903 case ICmpInst::ICMP_SLE:
5904 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5905 case ICmpInst::ICMP_UGE:
5906 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5907 case ICmpInst::ICMP_SGE:
5908 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005909 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005910
5911 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005912 // in the input. If this comparison is a normal comparison, it demands all
5913 // bits, if it is a sign bit comparison, it only demands the sign bit.
5914
5915 bool UnusedBit;
5916 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5917
Reid Spencer0460fb32007-03-22 20:36:03 +00005918 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5919 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005920 if (SimplifyDemandedBits(Op0,
5921 isSignBit ? APInt::getSignBit(BitWidth)
5922 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005923 KnownZero, KnownOne, 0))
5924 return &I;
5925
5926 // Given the known and unknown bits, compute a range that the LHS could be
5927 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005928 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005929 // Compute the Min, Max and RHS values based on the known bits. For the
5930 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005931 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5932 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005933 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005934 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5935 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005936 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005937 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5938 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005939 }
5940 switch (I.getPredicate()) { // LE/GE have been folded already.
5941 default: assert(0 && "Unknown icmp opcode!");
5942 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005943 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005944 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005945 break;
5946 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005947 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005948 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005949 break;
5950 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005951 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005952 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005953 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005954 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 break;
5956 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005957 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005959 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005960 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005961 break;
5962 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005963 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005964 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005965 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005966 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005967 break;
5968 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005969 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005970 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005971 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005972 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005973 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005974 }
5975 }
5976
Reid Spencere4d87aa2006-12-23 06:05:41 +00005977 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005978 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005979 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005980 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005981 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5982 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005983 }
5984
Chris Lattner01deb9d2007-04-03 17:43:25 +00005985 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005986 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5987 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5988 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005989 case Instruction::GetElementPtr:
5990 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005991 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005992 bool isAllZeros = true;
5993 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5994 if (!isa<Constant>(LHSI->getOperand(i)) ||
5995 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5996 isAllZeros = false;
5997 break;
5998 }
5999 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00006001 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6002 }
6003 break;
6004
Chris Lattner6970b662005-04-23 15:31:55 +00006005 case Instruction::PHI:
6006 if (Instruction *NV = FoldOpIntoPhi(I))
6007 return NV;
6008 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006009 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006010 // If either operand of the select is a constant, we can fold the
6011 // comparison into the select arms, which will cause one to be
6012 // constant folded and the select turned into a bitwise or.
6013 Value *Op1 = 0, *Op2 = 0;
6014 if (LHSI->hasOneUse()) {
6015 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6016 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006017 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6018 // Insert a new ICmp of the other select operand.
6019 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6020 LHSI->getOperand(2), RHSC,
6021 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006022 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6023 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006024 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6025 // Insert a new ICmp of the other select operand.
6026 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6027 LHSI->getOperand(1), RHSC,
6028 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006029 }
6030 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006031
Chris Lattner6970b662005-04-23 15:31:55 +00006032 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006033 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006034 break;
6035 }
Chris Lattner4802d902007-04-06 18:57:34 +00006036 case Instruction::Malloc:
6037 // If we have (malloc != null), and if the malloc has a single use, we
6038 // can assume it is successful and remove the malloc.
6039 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6040 AddToWorkList(LHSI);
6041 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006042 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006043 }
6044 break;
6045 }
Chris Lattner6970b662005-04-23 15:31:55 +00006046 }
6047
Reid Spencere4d87aa2006-12-23 06:05:41 +00006048 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006049 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006050 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006051 return NI;
6052 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006053 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6054 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006055 return NI;
6056
Reid Spencere4d87aa2006-12-23 06:05:41 +00006057 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006058 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6059 // now.
6060 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6061 if (isa<PointerType>(Op0->getType()) &&
6062 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006063 // We keep moving the cast from the left operand over to the right
6064 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006065 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006066
Chris Lattner57d86372007-01-06 01:45:59 +00006067 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6068 // so eliminate it as well.
6069 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6070 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006071
Chris Lattnerde90b762003-11-03 04:25:02 +00006072 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006073 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006074 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006075 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006076 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006077 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006078 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006079 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006080 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006081 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006082 }
Chris Lattner57d86372007-01-06 01:45:59 +00006083 }
6084
6085 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006086 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006087 // This comes up when you have code like
6088 // int X = A < B;
6089 // if (X) ...
6090 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006091 // with a constant or another cast from the same type.
6092 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006093 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006094 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006095 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006096
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006097 // ~x < ~y --> y < x
6098 { Value *A, *B;
6099 if (match(Op0, m_Not(m_Value(A))) &&
6100 match(Op1, m_Not(m_Value(B))))
6101 return new ICmpInst(I.getPredicate(), B, A);
6102 }
6103
Chris Lattner65b72ba2006-09-18 04:22:48 +00006104 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006105 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006106
6107 // -x == -y --> x == y
6108 if (match(Op0, m_Neg(m_Value(A))) &&
6109 match(Op1, m_Neg(m_Value(B))))
6110 return new ICmpInst(I.getPredicate(), A, B);
6111
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006112 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6113 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6114 Value *OtherVal = A == Op1 ? B : A;
6115 return new ICmpInst(I.getPredicate(), OtherVal,
6116 Constant::getNullValue(A->getType()));
6117 }
6118
6119 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6120 // A^c1 == C^c2 --> A == C^(c1^c2)
6121 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6122 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6123 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006124 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006125 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006126 return new ICmpInst(I.getPredicate(), A,
6127 InsertNewInstBefore(Xor, I));
6128 }
6129
6130 // A^B == A^D -> B == D
6131 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6132 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6133 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6134 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6135 }
6136 }
6137
6138 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6139 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006140 // A == (A^B) -> B == 0
6141 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006142 return new ICmpInst(I.getPredicate(), OtherVal,
6143 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006144 }
6145 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006146 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006147 return new ICmpInst(I.getPredicate(), B,
6148 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006149 }
6150 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006151 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006152 return new ICmpInst(I.getPredicate(), B,
6153 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006154 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006155
Chris Lattner9c2328e2006-11-14 06:06:06 +00006156 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6157 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6158 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6159 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6160 Value *X = 0, *Y = 0, *Z = 0;
6161
6162 if (A == C) {
6163 X = B; Y = D; Z = A;
6164 } else if (A == D) {
6165 X = B; Y = C; Z = A;
6166 } else if (B == C) {
6167 X = A; Y = D; Z = B;
6168 } else if (B == D) {
6169 X = A; Y = C; Z = B;
6170 }
6171
6172 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006173 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6174 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006175 I.setOperand(0, Op1);
6176 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6177 return &I;
6178 }
6179 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006180 }
Chris Lattner7e708292002-06-25 16:13:24 +00006181 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006182}
6183
Chris Lattner562ef782007-06-20 23:46:26 +00006184
6185/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6186/// and CmpRHS are both known to be integer constants.
6187Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6188 ConstantInt *DivRHS) {
6189 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6190 const APInt &CmpRHSV = CmpRHS->getValue();
6191
6192 // FIXME: If the operand types don't match the type of the divide
6193 // then don't attempt this transform. The code below doesn't have the
6194 // logic to deal with a signed divide and an unsigned compare (and
6195 // vice versa). This is because (x /s C1) <s C2 produces different
6196 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6197 // (x /u C1) <u C2. Simply casting the operands and result won't
6198 // work. :( The if statement below tests that condition and bails
6199 // if it finds it.
6200 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6201 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6202 return 0;
6203 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006204 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006205
6206 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6207 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6208 // C2 (CI). By solving for X we can turn this into a range check
6209 // instead of computing a divide.
6210 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6211
6212 // Determine if the product overflows by seeing if the product is
6213 // not equal to the divide. Make sure we do the same kind of divide
6214 // as in the LHS instruction that we're folding.
6215 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6216 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6217
6218 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006219 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006220
Chris Lattner1dbfd482007-06-21 18:11:19 +00006221 // Figure out the interval that is being checked. For example, a comparison
6222 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6223 // Compute this interval based on the constants involved and the signedness of
6224 // the compare/divide. This computes a half-open interval, keeping track of
6225 // whether either value in the interval overflows. After analysis each
6226 // overflow variable is set to 0 if it's corresponding bound variable is valid
6227 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6228 int LoOverflow = 0, HiOverflow = 0;
6229 ConstantInt *LoBound = 0, *HiBound = 0;
6230
6231
Chris Lattner562ef782007-06-20 23:46:26 +00006232 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006233 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006234 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006235 HiOverflow = LoOverflow = ProdOV;
6236 if (!HiOverflow)
6237 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006238 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006239 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006240 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006241 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6242 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006243 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006244 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6245 HiOverflow = LoOverflow = ProdOV;
6246 if (!HiOverflow)
6247 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006248 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006249 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006250 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6251 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006252 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006253 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006254 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006255 }
Dan Gohman76491272008-02-13 22:09:18 +00006256 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006257 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006258 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006259 LoBound = AddOne(DivRHS);
6260 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006261 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6262 HiOverflow = 1; // [INTMIN+1, overflow)
6263 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6264 }
Dan Gohman76491272008-02-13 22:09:18 +00006265 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006266 // e.g. X/-5 op 3 --> [-19, -14)
6267 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006268 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006269 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006270 HiBound = AddOne(Prod);
6271 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006272 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006273 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006274 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006275 HiBound = Subtract(Prod, DivRHS);
6276 }
6277
Chris Lattner1dbfd482007-06-21 18:11:19 +00006278 // Dividing by a negative swaps the condition. LT <-> GT
6279 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006280 }
6281
6282 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006283 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006284 default: assert(0 && "Unhandled icmp opcode!");
6285 case ICmpInst::ICMP_EQ:
6286 if (LoOverflow && HiOverflow)
6287 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6288 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006289 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006290 ICmpInst::ICMP_UGE, X, LoBound);
6291 else if (LoOverflow)
6292 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6293 ICmpInst::ICMP_ULT, X, HiBound);
6294 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006295 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006296 case ICmpInst::ICMP_NE:
6297 if (LoOverflow && HiOverflow)
6298 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6299 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006300 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006301 ICmpInst::ICMP_ULT, X, LoBound);
6302 else if (LoOverflow)
6303 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6304 ICmpInst::ICMP_UGE, X, HiBound);
6305 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006306 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006307 case ICmpInst::ICMP_ULT:
6308 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006309 if (LoOverflow == +1) // Low bound is greater than input range.
6310 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6311 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006312 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006313 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006314 case ICmpInst::ICMP_UGT:
6315 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006316 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006317 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006318 else if (HiOverflow == -1) // High bound less than input range.
6319 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6320 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006321 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6322 else
6323 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6324 }
6325}
6326
6327
Chris Lattner01deb9d2007-04-03 17:43:25 +00006328/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6329///
6330Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6331 Instruction *LHSI,
6332 ConstantInt *RHS) {
6333 const APInt &RHSV = RHS->getValue();
6334
6335 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006336 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006337 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6338 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6339 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006340 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6341 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006342 Value *CompareVal = LHSI->getOperand(0);
6343
6344 // If the sign bit of the XorCST is not set, there is no change to
6345 // the operation, just stop using the Xor.
6346 if (!XorCST->getValue().isNegative()) {
6347 ICI.setOperand(0, CompareVal);
6348 AddToWorkList(LHSI);
6349 return &ICI;
6350 }
6351
6352 // Was the old condition true if the operand is positive?
6353 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6354
6355 // If so, the new one isn't.
6356 isTrueIfPositive ^= true;
6357
6358 if (isTrueIfPositive)
6359 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6360 else
6361 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6362 }
6363 }
6364 break;
6365 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6366 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6367 LHSI->getOperand(0)->hasOneUse()) {
6368 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6369
6370 // If the LHS is an AND of a truncating cast, we can widen the
6371 // and/compare to be the input width without changing the value
6372 // produced, eliminating a cast.
6373 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6374 // We can do this transformation if either the AND constant does not
6375 // have its sign bit set or if it is an equality comparison.
6376 // Extending a relational comparison when we're checking the sign
6377 // bit would not work.
6378 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006379 (ICI.isEquality() ||
6380 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006381 uint32_t BitWidth =
6382 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6383 APInt NewCST = AndCST->getValue();
6384 NewCST.zext(BitWidth);
6385 APInt NewCI = RHSV;
6386 NewCI.zext(BitWidth);
6387 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006388 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006389 ConstantInt::get(NewCST),LHSI->getName());
6390 InsertNewInstBefore(NewAnd, ICI);
6391 return new ICmpInst(ICI.getPredicate(), NewAnd,
6392 ConstantInt::get(NewCI));
6393 }
6394 }
6395
6396 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6397 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6398 // happens a LOT in code produced by the C front-end, for bitfield
6399 // access.
6400 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6401 if (Shift && !Shift->isShift())
6402 Shift = 0;
6403
6404 ConstantInt *ShAmt;
6405 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6406 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6407 const Type *AndTy = AndCST->getType(); // Type of the and.
6408
6409 // We can fold this as long as we can't shift unknown bits
6410 // into the mask. This can only happen with signed shift
6411 // rights, as they sign-extend.
6412 if (ShAmt) {
6413 bool CanFold = Shift->isLogicalShift();
6414 if (!CanFold) {
6415 // To test for the bad case of the signed shr, see if any
6416 // of the bits shifted in could be tested after the mask.
6417 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6418 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6419
6420 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6421 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6422 AndCST->getValue()) == 0)
6423 CanFold = true;
6424 }
6425
6426 if (CanFold) {
6427 Constant *NewCst;
6428 if (Shift->getOpcode() == Instruction::Shl)
6429 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6430 else
6431 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6432
6433 // Check to see if we are shifting out any of the bits being
6434 // compared.
6435 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6436 // If we shifted bits out, the fold is not going to work out.
6437 // As a special case, check to see if this means that the
6438 // result is always true or false now.
6439 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6440 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6441 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6442 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6443 } else {
6444 ICI.setOperand(1, NewCst);
6445 Constant *NewAndCST;
6446 if (Shift->getOpcode() == Instruction::Shl)
6447 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6448 else
6449 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6450 LHSI->setOperand(1, NewAndCST);
6451 LHSI->setOperand(0, Shift->getOperand(0));
6452 AddToWorkList(Shift); // Shift is dead.
6453 AddUsesToWorkList(ICI);
6454 return &ICI;
6455 }
6456 }
6457 }
6458
6459 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6460 // preferable because it allows the C<<Y expression to be hoisted out
6461 // of a loop if Y is invariant and X is not.
6462 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6463 ICI.isEquality() && !Shift->isArithmeticShift() &&
6464 isa<Instruction>(Shift->getOperand(0))) {
6465 // Compute C << Y.
6466 Value *NS;
6467 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006468 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006469 Shift->getOperand(1), "tmp");
6470 } else {
6471 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006472 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006473 Shift->getOperand(1), "tmp");
6474 }
6475 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6476
6477 // Compute X & (C << Y).
6478 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006479 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006480 InsertNewInstBefore(NewAnd, ICI);
6481
6482 ICI.setOperand(0, NewAnd);
6483 return &ICI;
6484 }
6485 }
6486 break;
6487
Chris Lattnera0141b92007-07-15 20:42:37 +00006488 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6489 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6490 if (!ShAmt) break;
6491
6492 uint32_t TypeBits = RHSV.getBitWidth();
6493
6494 // Check that the shift amount is in range. If not, don't perform
6495 // undefined shifts. When the shift is visited it will be
6496 // simplified.
6497 if (ShAmt->uge(TypeBits))
6498 break;
6499
6500 if (ICI.isEquality()) {
6501 // If we are comparing against bits always shifted out, the
6502 // comparison cannot succeed.
6503 Constant *Comp =
6504 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6505 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6506 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6507 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6508 return ReplaceInstUsesWith(ICI, Cst);
6509 }
6510
6511 if (LHSI->hasOneUse()) {
6512 // Otherwise strength reduce the shift into an and.
6513 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6514 Constant *Mask =
6515 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006516
Chris Lattnera0141b92007-07-15 20:42:37 +00006517 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006518 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006519 Mask, LHSI->getName()+".mask");
6520 Value *And = InsertNewInstBefore(AndI, ICI);
6521 return new ICmpInst(ICI.getPredicate(), And,
6522 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006523 }
6524 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006525
6526 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6527 bool TrueIfSigned = false;
6528 if (LHSI->hasOneUse() &&
6529 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6530 // (X << 31) <s 0 --> (X&1) != 0
6531 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6532 (TypeBits-ShAmt->getZExtValue()-1));
6533 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006534 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006535 Mask, LHSI->getName()+".mask");
6536 Value *And = InsertNewInstBefore(AndI, ICI);
6537
6538 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6539 And, Constant::getNullValue(And->getType()));
6540 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006541 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006542 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006543
6544 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006545 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006546 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006547 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006548 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006549
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006550 // Check that the shift amount is in range. If not, don't perform
6551 // undefined shifts. When the shift is visited it will be
6552 // simplified.
6553 uint32_t TypeBits = RHSV.getBitWidth();
6554 if (ShAmt->uge(TypeBits))
6555 break;
6556
6557 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006558
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006559 // If we are comparing against bits always shifted out, the
6560 // comparison cannot succeed.
6561 APInt Comp = RHSV << ShAmtVal;
6562 if (LHSI->getOpcode() == Instruction::LShr)
6563 Comp = Comp.lshr(ShAmtVal);
6564 else
6565 Comp = Comp.ashr(ShAmtVal);
6566
6567 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6568 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6569 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6570 return ReplaceInstUsesWith(ICI, Cst);
6571 }
6572
6573 // Otherwise, check to see if the bits shifted out are known to be zero.
6574 // If so, we can compare against the unshifted value:
6575 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006576 if (LHSI->hasOneUse() &&
6577 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006578 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6579 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6580 ConstantExpr::getShl(RHS, ShAmt));
6581 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006582
Evan Chengf30752c2008-04-23 00:38:06 +00006583 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006584 // Otherwise strength reduce the shift into an and.
6585 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6586 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006587
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006588 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006589 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006590 Mask, LHSI->getName()+".mask");
6591 Value *And = InsertNewInstBefore(AndI, ICI);
6592 return new ICmpInst(ICI.getPredicate(), And,
6593 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006594 }
6595 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006596 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006597
6598 case Instruction::SDiv:
6599 case Instruction::UDiv:
6600 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6601 // Fold this div into the comparison, producing a range check.
6602 // Determine, based on the divide type, what the range is being
6603 // checked. If there is an overflow on the low or high side, remember
6604 // it, otherwise compute the range [low, hi) bounding the new value.
6605 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006606 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6607 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6608 DivRHS))
6609 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006610 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006611
6612 case Instruction::Add:
6613 // Fold: icmp pred (add, X, C1), C2
6614
6615 if (!ICI.isEquality()) {
6616 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6617 if (!LHSC) break;
6618 const APInt &LHSV = LHSC->getValue();
6619
6620 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6621 .subtract(LHSV);
6622
6623 if (ICI.isSignedPredicate()) {
6624 if (CR.getLower().isSignBit()) {
6625 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6626 ConstantInt::get(CR.getUpper()));
6627 } else if (CR.getUpper().isSignBit()) {
6628 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6629 ConstantInt::get(CR.getLower()));
6630 }
6631 } else {
6632 if (CR.getLower().isMinValue()) {
6633 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6634 ConstantInt::get(CR.getUpper()));
6635 } else if (CR.getUpper().isMinValue()) {
6636 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6637 ConstantInt::get(CR.getLower()));
6638 }
6639 }
6640 }
6641 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006642 }
6643
6644 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6645 if (ICI.isEquality()) {
6646 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6647
6648 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6649 // the second operand is a constant, simplify a bit.
6650 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6651 switch (BO->getOpcode()) {
6652 case Instruction::SRem:
6653 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6654 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6655 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6656 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6657 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006658 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006659 BO->getName());
6660 InsertNewInstBefore(NewRem, ICI);
6661 return new ICmpInst(ICI.getPredicate(), NewRem,
6662 Constant::getNullValue(BO->getType()));
6663 }
6664 }
6665 break;
6666 case Instruction::Add:
6667 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6668 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6669 if (BO->hasOneUse())
6670 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6671 Subtract(RHS, BOp1C));
6672 } else if (RHSV == 0) {
6673 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6674 // efficiently invertible, or if the add has just this one use.
6675 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6676
6677 if (Value *NegVal = dyn_castNegVal(BOp1))
6678 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6679 else if (Value *NegVal = dyn_castNegVal(BOp0))
6680 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6681 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006682 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006683 InsertNewInstBefore(Neg, ICI);
6684 Neg->takeName(BO);
6685 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6686 }
6687 }
6688 break;
6689 case Instruction::Xor:
6690 // For the xor case, we can xor two constants together, eliminating
6691 // the explicit xor.
6692 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6693 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6694 ConstantExpr::getXor(RHS, BOC));
6695
6696 // FALLTHROUGH
6697 case Instruction::Sub:
6698 // Replace (([sub|xor] A, B) != 0) with (A != B)
6699 if (RHSV == 0)
6700 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6701 BO->getOperand(1));
6702 break;
6703
6704 case Instruction::Or:
6705 // If bits are being or'd in that are not present in the constant we
6706 // are comparing against, then the comparison could never succeed!
6707 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6708 Constant *NotCI = ConstantExpr::getNot(RHS);
6709 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6710 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6711 isICMP_NE));
6712 }
6713 break;
6714
6715 case Instruction::And:
6716 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6717 // If bits are being compared against that are and'd out, then the
6718 // comparison can never succeed!
6719 if ((RHSV & ~BOC->getValue()) != 0)
6720 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6721 isICMP_NE));
6722
6723 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6724 if (RHS == BOC && RHSV.isPowerOf2())
6725 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6726 ICmpInst::ICMP_NE, LHSI,
6727 Constant::getNullValue(RHS->getType()));
6728
6729 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6730 if (isSignBit(BOC)) {
6731 Value *X = BO->getOperand(0);
6732 Constant *Zero = Constant::getNullValue(X->getType());
6733 ICmpInst::Predicate pred = isICMP_NE ?
6734 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6735 return new ICmpInst(pred, X, Zero);
6736 }
6737
6738 // ((X & ~7) == 0) --> X < 8
6739 if (RHSV == 0 && isHighOnes(BOC)) {
6740 Value *X = BO->getOperand(0);
6741 Constant *NegX = ConstantExpr::getNeg(BOC);
6742 ICmpInst::Predicate pred = isICMP_NE ?
6743 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6744 return new ICmpInst(pred, X, NegX);
6745 }
6746 }
6747 default: break;
6748 }
6749 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6750 // Handle icmp {eq|ne} <intrinsic>, intcst.
6751 if (II->getIntrinsicID() == Intrinsic::bswap) {
6752 AddToWorkList(II);
6753 ICI.setOperand(0, II->getOperand(1));
6754 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6755 return &ICI;
6756 }
6757 }
6758 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006759 // If the LHS is a cast from an integral value of the same size,
6760 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006761 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6762 Value *CastOp = Cast->getOperand(0);
6763 const Type *SrcTy = CastOp->getType();
6764 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6765 if (SrcTy->isInteger() &&
6766 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6767 // If this is an unsigned comparison, try to make the comparison use
6768 // smaller constant values.
6769 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6770 // X u< 128 => X s> -1
6771 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6772 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6773 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6774 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6775 // X u> 127 => X s< 0
6776 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6777 Constant::getNullValue(SrcTy));
6778 }
6779 }
6780 }
6781 }
6782 return 0;
6783}
6784
6785/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6786/// We only handle extending casts so far.
6787///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006788Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6789 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006790 Value *LHSCIOp = LHSCI->getOperand(0);
6791 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006792 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006793 Value *RHSCIOp;
6794
Chris Lattner8c756c12007-05-05 22:41:33 +00006795 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6796 // integer type is the same size as the pointer type.
6797 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6798 getTargetData().getPointerSizeInBits() ==
6799 cast<IntegerType>(DestTy)->getBitWidth()) {
6800 Value *RHSOp = 0;
6801 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006802 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006803 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6804 RHSOp = RHSC->getOperand(0);
6805 // If the pointer types don't match, insert a bitcast.
6806 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006807 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006808 }
6809
6810 if (RHSOp)
6811 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6812 }
6813
6814 // The code below only handles extension cast instructions, so far.
6815 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006816 if (LHSCI->getOpcode() != Instruction::ZExt &&
6817 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006818 return 0;
6819
Reid Spencere4d87aa2006-12-23 06:05:41 +00006820 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6821 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006822
Reid Spencere4d87aa2006-12-23 06:05:41 +00006823 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006824 // Not an extension from the same type?
6825 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006826 if (RHSCIOp->getType() != LHSCIOp->getType())
6827 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006828
Nick Lewycky4189a532008-01-28 03:48:02 +00006829 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006830 // and the other is a zext), then we can't handle this.
6831 if (CI->getOpcode() != LHSCI->getOpcode())
6832 return 0;
6833
Nick Lewycky4189a532008-01-28 03:48:02 +00006834 // Deal with equality cases early.
6835 if (ICI.isEquality())
6836 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6837
6838 // A signed comparison of sign extended values simplifies into a
6839 // signed comparison.
6840 if (isSignedCmp && isSignedExt)
6841 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6842
6843 // The other three cases all fold into an unsigned comparison.
6844 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006845 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006846
Reid Spencere4d87aa2006-12-23 06:05:41 +00006847 // If we aren't dealing with a constant on the RHS, exit early
6848 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6849 if (!CI)
6850 return 0;
6851
6852 // Compute the constant that would happen if we truncated to SrcTy then
6853 // reextended to DestTy.
6854 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6855 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6856
6857 // If the re-extended constant didn't change...
6858 if (Res2 == CI) {
6859 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6860 // For example, we might have:
6861 // %A = sext short %X to uint
6862 // %B = icmp ugt uint %A, 1330
6863 // It is incorrect to transform this into
6864 // %B = icmp ugt short %X, 1330
6865 // because %A may have negative value.
6866 //
6867 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6868 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006869 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006870 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6871 else
6872 return 0;
6873 }
6874
6875 // The re-extended constant changed so the constant cannot be represented
6876 // in the shorter type. Consequently, we cannot emit a simple comparison.
6877
6878 // First, handle some easy cases. We know the result cannot be equal at this
6879 // point so handle the ICI.isEquality() cases
6880 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006881 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006882 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006883 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006884
6885 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6886 // should have been folded away previously and not enter in here.
6887 Value *Result;
6888 if (isSignedCmp) {
6889 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006890 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006891 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006892 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006893 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006894 } else {
6895 // We're performing an unsigned comparison.
6896 if (isSignedExt) {
6897 // We're performing an unsigned comp with a sign extended value.
6898 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006899 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006900 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6901 NegOne, ICI.getName()), ICI);
6902 } else {
6903 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006904 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006905 }
6906 }
6907
6908 // Finally, return the value computed.
6909 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6910 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6911 return ReplaceInstUsesWith(ICI, Result);
6912 } else {
6913 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6914 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6915 "ICmp should be folded!");
6916 if (Constant *CI = dyn_cast<Constant>(Result))
6917 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6918 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006919 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006920 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006921}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006922
Reid Spencer832254e2007-02-02 02:16:23 +00006923Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6924 return commonShiftTransforms(I);
6925}
6926
6927Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6928 return commonShiftTransforms(I);
6929}
6930
6931Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006932 if (Instruction *R = commonShiftTransforms(I))
6933 return R;
6934
6935 Value *Op0 = I.getOperand(0);
6936
6937 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6938 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6939 if (CSI->isAllOnesValue())
6940 return ReplaceInstUsesWith(I, CSI);
6941
6942 // See if we can turn a signed shr into an unsigned shr.
6943 if (MaskedValueIsZero(Op0,
6944 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006945 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006946
6947 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006948}
6949
6950Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6951 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006952 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006953
6954 // shl X, 0 == X and shr X, 0 == X
6955 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006956 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006957 Op0 == Constant::getNullValue(Op0->getType()))
6958 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006959
Reid Spencere4d87aa2006-12-23 06:05:41 +00006960 if (isa<UndefValue>(Op0)) {
6961 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006962 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006963 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006964 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6965 }
6966 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006967 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6968 return ReplaceInstUsesWith(I, Op0);
6969 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006971 }
6972
Chris Lattner2eefe512004-04-09 19:05:30 +00006973 // Try to fold constant and into select arguments.
6974 if (isa<Constant>(Op0))
6975 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006976 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006977 return R;
6978
Reid Spencerb83eb642006-10-20 07:07:24 +00006979 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006980 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6981 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006982 return 0;
6983}
6984
Reid Spencerb83eb642006-10-20 07:07:24 +00006985Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006986 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006987 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006988
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006989 // See if we can simplify any instructions used by the instruction whose sole
6990 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006991 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6992 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6993 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006994 KnownZero, KnownOne))
6995 return &I;
6996
Chris Lattner4d5542c2006-01-06 07:12:35 +00006997 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6998 // of a signed value.
6999 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007000 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007001 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00007002 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7003 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007004 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007005 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007006 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007007 }
7008
7009 // ((X*C1) << C2) == (X * (C1 << C2))
7010 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7011 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7012 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007013 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007014 ConstantExpr::getShl(BOOp, Op1));
7015
7016 // Try to fold constant and into select arguments.
7017 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7018 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7019 return R;
7020 if (isa<PHINode>(Op0))
7021 if (Instruction *NV = FoldOpIntoPhi(I))
7022 return NV;
7023
Chris Lattner8999dd32007-12-22 09:07:47 +00007024 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7025 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7026 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7027 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7028 // place. Don't try to do this transformation in this case. Also, we
7029 // require that the input operand is a shift-by-constant so that we have
7030 // confidence that the shifts will get folded together. We could do this
7031 // xform in more cases, but it is unlikely to be profitable.
7032 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7033 isa<ConstantInt>(TrOp->getOperand(1))) {
7034 // Okay, we'll do this xform. Make the shift of shift.
7035 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007036 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007037 I.getName());
7038 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7039
7040 // For logical shifts, the truncation has the effect of making the high
7041 // part of the register be zeros. Emulate this by inserting an AND to
7042 // clear the top bits as needed. This 'and' will usually be zapped by
7043 // other xforms later if dead.
7044 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7045 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7046 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7047
7048 // The mask we constructed says what the trunc would do if occurring
7049 // between the shifts. We want to know the effect *after* the second
7050 // shift. We know that it is a logical shift by a constant, so adjust the
7051 // mask as appropriate.
7052 if (I.getOpcode() == Instruction::Shl)
7053 MaskV <<= Op1->getZExtValue();
7054 else {
7055 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7056 MaskV = MaskV.lshr(Op1->getZExtValue());
7057 }
7058
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007059 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007060 TI->getName());
7061 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7062
7063 // Return the value truncated to the interesting size.
7064 return new TruncInst(And, I.getType());
7065 }
7066 }
7067
Chris Lattner4d5542c2006-01-06 07:12:35 +00007068 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007069 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7070 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7071 Value *V1, *V2;
7072 ConstantInt *CC;
7073 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007074 default: break;
7075 case Instruction::Add:
7076 case Instruction::And:
7077 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007078 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007079 // These operators commute.
7080 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007081 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7082 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007083 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007084 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007085 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007086 Op0BO->getName());
7087 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007088 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007089 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007090 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007091 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007092 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007093 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007094 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007095 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007096
Chris Lattner150f12a2005-09-18 06:30:59 +00007097 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007098 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007099 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007100 match(Op0BOOp1,
7101 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007102 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7103 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007104 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007105 Op0BO->getOperand(0), Op1,
7106 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007107 InsertNewInstBefore(YS, I); // (Y << C)
7108 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007109 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007110 V1->getName()+".mask");
7111 InsertNewInstBefore(XM, I); // X & (CC << C)
7112
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007113 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007114 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007115 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007116
Reid Spencera07cb7d2007-02-02 14:41:37 +00007117 // FALL THROUGH.
7118 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007119 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007120 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7121 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007122 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007123 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007124 Op0BO->getOperand(1), Op1,
7125 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007126 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007127 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007128 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007129 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007130 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007131 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007132 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007133 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007134 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007135
Chris Lattner13d4ab42006-05-31 21:14:00 +00007136 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007137 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7138 match(Op0BO->getOperand(0),
7139 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007140 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007141 cast<BinaryOperator>(Op0BO->getOperand(0))
7142 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007143 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007144 Op0BO->getOperand(1), Op1,
7145 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007146 InsertNewInstBefore(YS, I); // (Y << C)
7147 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007148 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007149 V1->getName()+".mask");
7150 InsertNewInstBefore(XM, I); // X & (CC << C)
7151
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007152 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007153 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007154
Chris Lattner11021cb2005-09-18 05:12:10 +00007155 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007156 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007157 }
7158
7159
7160 // If the operand is an bitwise operator with a constant RHS, and the
7161 // shift is the only use, we can pull it out of the shift.
7162 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7163 bool isValid = true; // Valid only for And, Or, Xor
7164 bool highBitSet = false; // Transform if high bit of constant set?
7165
7166 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007167 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007168 case Instruction::Add:
7169 isValid = isLeftShift;
7170 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007171 case Instruction::Or:
7172 case Instruction::Xor:
7173 highBitSet = false;
7174 break;
7175 case Instruction::And:
7176 highBitSet = true;
7177 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007178 }
7179
7180 // If this is a signed shift right, and the high bit is modified
7181 // by the logical operation, do not perform the transformation.
7182 // The highBitSet boolean indicates the value of the high bit of
7183 // the constant which would cause it to be modified for this
7184 // operation.
7185 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007186 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007187 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007188
7189 if (isValid) {
7190 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7191
7192 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007193 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007194 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007195 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007196
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007197 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007198 NewRHS);
7199 }
7200 }
7201 }
7202 }
7203
Chris Lattnerad0124c2006-01-06 07:52:12 +00007204 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007205 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7206 if (ShiftOp && !ShiftOp->isShift())
7207 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007208
Reid Spencerb83eb642006-10-20 07:07:24 +00007209 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007210 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007211 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7212 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007213 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7214 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7215 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007216
Zhou Sheng4351c642007-04-02 08:20:41 +00007217 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007218 if (AmtSum > TypeBits)
7219 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007220
7221 const IntegerType *Ty = cast<IntegerType>(I.getType());
7222
7223 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007224 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007225 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007226 ConstantInt::get(Ty, AmtSum));
7227 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7228 I.getOpcode() == Instruction::AShr) {
7229 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007230 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007231 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7232 I.getOpcode() == Instruction::LShr) {
7233 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7234 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007235 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007236 InsertNewInstBefore(Shift, I);
7237
Zhou Shenge9e03f62007-03-28 15:02:20 +00007238 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007239 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007240 }
7241
Chris Lattnerb87056f2007-02-05 00:57:54 +00007242 // Okay, if we get here, one shift must be left, and the other shift must be
7243 // right. See if the amounts are equal.
7244 if (ShiftAmt1 == ShiftAmt2) {
7245 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7246 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007247 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007248 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007249 }
7250 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7251 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007252 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007253 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007254 }
7255 // We can simplify ((X << C) >>s C) into a trunc + sext.
7256 // NOTE: we could do this for any C, but that would make 'unusual' integer
7257 // types. For now, just stick to ones well-supported by the code
7258 // generators.
7259 const Type *SExtType = 0;
7260 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007261 case 1 :
7262 case 8 :
7263 case 16 :
7264 case 32 :
7265 case 64 :
7266 case 128:
7267 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7268 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007269 default: break;
7270 }
7271 if (SExtType) {
7272 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7273 InsertNewInstBefore(NewTrunc, I);
7274 return new SExtInst(NewTrunc, Ty);
7275 }
7276 // Otherwise, we can't handle it yet.
7277 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007278 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007279
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007280 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007281 if (I.getOpcode() == Instruction::Shl) {
7282 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7283 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007284 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007285 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007286 InsertNewInstBefore(Shift, I);
7287
Reid Spencer55702aa2007-03-25 21:11:44 +00007288 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007289 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007290 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007291
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007292 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007293 if (I.getOpcode() == Instruction::LShr) {
7294 assert(ShiftOp->getOpcode() == Instruction::Shl);
7295 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007296 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007297 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007298
Reid Spencerd5e30f02007-03-26 17:18:58 +00007299 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007300 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007301 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007302
7303 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7304 } else {
7305 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007306 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007307
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007308 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007309 if (I.getOpcode() == Instruction::Shl) {
7310 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7311 ShiftOp->getOpcode() == Instruction::AShr);
7312 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007313 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007314 ConstantInt::get(Ty, ShiftDiff));
7315 InsertNewInstBefore(Shift, I);
7316
Reid Spencer55702aa2007-03-25 21:11:44 +00007317 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007318 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007319 }
7320
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007321 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007322 if (I.getOpcode() == Instruction::LShr) {
7323 assert(ShiftOp->getOpcode() == Instruction::Shl);
7324 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007325 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007326 InsertNewInstBefore(Shift, I);
7327
Reid Spencer68d27cf2007-03-26 23:45:51 +00007328 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007329 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007330 }
7331
7332 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007333 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007334 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007335 return 0;
7336}
7337
Chris Lattnera1be5662002-05-02 17:06:02 +00007338
Chris Lattnercfd65102005-10-29 04:36:15 +00007339/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7340/// expression. If so, decompose it, returning some value X, such that Val is
7341/// X*Scale+Offset.
7342///
7343static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007344 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007345 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007346 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007347 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007348 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007349 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007350 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7351 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7352 if (I->getOpcode() == Instruction::Shl) {
7353 // This is a value scaled by '1 << the shift amt'.
7354 Scale = 1U << RHS->getZExtValue();
7355 Offset = 0;
7356 return I->getOperand(0);
7357 } else if (I->getOpcode() == Instruction::Mul) {
7358 // This value is scaled by 'RHS'.
7359 Scale = RHS->getZExtValue();
7360 Offset = 0;
7361 return I->getOperand(0);
7362 } else if (I->getOpcode() == Instruction::Add) {
7363 // We have X+C. Check to see if we really have (X*C2)+C1,
7364 // where C1 is divisible by C2.
7365 unsigned SubScale;
7366 Value *SubVal =
7367 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7368 Offset += RHS->getZExtValue();
7369 Scale = SubScale;
7370 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007371 }
7372 }
7373 }
7374
7375 // Otherwise, we can't look past this.
7376 Scale = 1;
7377 Offset = 0;
7378 return Val;
7379}
7380
7381
Chris Lattnerb3f83972005-10-24 06:03:58 +00007382/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7383/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007384Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007385 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007386 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007387
Chris Lattnerb53c2382005-10-24 06:22:12 +00007388 // Remove any uses of AI that are dead.
7389 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007390
Chris Lattnerb53c2382005-10-24 06:22:12 +00007391 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7392 Instruction *User = cast<Instruction>(*UI++);
7393 if (isInstructionTriviallyDead(User)) {
7394 while (UI != E && *UI == User)
7395 ++UI; // If this instruction uses AI more than once, don't break UI.
7396
Chris Lattnerb53c2382005-10-24 06:22:12 +00007397 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007398 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007399 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007400 }
7401 }
7402
Chris Lattnerb3f83972005-10-24 06:03:58 +00007403 // Get the type really allocated and the type casted to.
7404 const Type *AllocElTy = AI.getAllocatedType();
7405 const Type *CastElTy = PTy->getElementType();
7406 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007407
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007408 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7409 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007410 if (CastElTyAlign < AllocElTyAlign) return 0;
7411
Chris Lattner39387a52005-10-24 06:35:18 +00007412 // If the allocation has multiple uses, only promote it if we are strictly
7413 // increasing the alignment of the resultant allocation. If we keep it the
7414 // same, we open the door to infinite loops of various kinds.
7415 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7416
Duncan Sands514ab342007-11-01 20:53:16 +00007417 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7418 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007419 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007420
Chris Lattner455fcc82005-10-29 03:19:53 +00007421 // See if we can satisfy the modulus by pulling a scale out of the array
7422 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007423 unsigned ArraySizeScale;
7424 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007425 Value *NumElements = // See if the array size is a decomposable linear expr.
7426 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7427
Chris Lattner455fcc82005-10-29 03:19:53 +00007428 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7429 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007430 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7431 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007432
Chris Lattner455fcc82005-10-29 03:19:53 +00007433 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7434 Value *Amt = 0;
7435 if (Scale == 1) {
7436 Amt = NumElements;
7437 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007438 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007439 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7440 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007441 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007442 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007443 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007444 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007445 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007446 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007447 }
7448
Jeff Cohen86796be2007-04-04 16:58:57 +00007449 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7450 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007451 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007452 Amt = InsertNewInstBefore(Tmp, AI);
7453 }
7454
Chris Lattnerb3f83972005-10-24 06:03:58 +00007455 AllocationInst *New;
7456 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007457 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007458 else
Chris Lattner6934a042007-02-11 01:23:03 +00007459 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007460 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007461 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007462
7463 // If the allocation has multiple uses, insert a cast and change all things
7464 // that used it to use the new cast. This will also hack on CI, but it will
7465 // die soon.
7466 if (!AI.hasOneUse()) {
7467 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007468 // New is the allocation instruction, pointer typed. AI is the original
7469 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7470 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007471 InsertNewInstBefore(NewCast, AI);
7472 AI.replaceAllUsesWith(NewCast);
7473 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007474 return ReplaceInstUsesWith(CI, New);
7475}
7476
Chris Lattner70074e02006-05-13 02:06:03 +00007477/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007478/// and return it as type Ty without inserting any new casts and without
7479/// changing the computed value. This is used by code that tries to decide
7480/// whether promoting or shrinking integer operations to wider or smaller types
7481/// will allow us to eliminate a truncate or extend.
7482///
7483/// This is a truncation operation if Ty is smaller than V->getType(), or an
7484/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007485bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7486 unsigned CastOpc,
7487 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007488 // We can always evaluate constants in another type.
7489 if (isa<ConstantInt>(V))
7490 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007491
7492 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007493 if (!I) return false;
7494
7495 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007496
Chris Lattner951626b2007-08-02 06:11:14 +00007497 // If this is an extension or truncate, we can often eliminate it.
7498 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7499 // If this is a cast from the destination type, we can trivially eliminate
7500 // it, and this will remove a cast overall.
7501 if (I->getOperand(0)->getType() == Ty) {
7502 // If the first operand is itself a cast, and is eliminable, do not count
7503 // this as an eliminable cast. We would prefer to eliminate those two
7504 // casts first.
7505 if (!isa<CastInst>(I->getOperand(0)))
7506 ++NumCastsRemoved;
7507 return true;
7508 }
7509 }
7510
7511 // We can't extend or shrink something that has multiple uses: doing so would
7512 // require duplicating the instruction in general, which isn't profitable.
7513 if (!I->hasOneUse()) return false;
7514
Chris Lattner70074e02006-05-13 02:06:03 +00007515 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007516 case Instruction::Add:
7517 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007518 case Instruction::And:
7519 case Instruction::Or:
7520 case Instruction::Xor:
7521 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007522 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7523 NumCastsRemoved) &&
7524 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7525 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007526
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007527 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007528 // A multiply can be truncated by truncating its operands.
7529 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7530 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7531 NumCastsRemoved) &&
7532 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7533 NumCastsRemoved);
7534
Chris Lattner46b96052006-11-29 07:18:39 +00007535 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007536 // If we are truncating the result of this SHL, and if it's a shift of a
7537 // constant amount, we can always perform a SHL in a smaller type.
7538 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007539 uint32_t BitWidth = Ty->getBitWidth();
7540 if (BitWidth < OrigTy->getBitWidth() &&
7541 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007542 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7543 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007544 }
7545 break;
7546 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007547 // If this is a truncate of a logical shr, we can truncate it to a smaller
7548 // lshr iff we know that the bits we would otherwise be shifting in are
7549 // already zeros.
7550 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007551 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7552 uint32_t BitWidth = Ty->getBitWidth();
7553 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007554 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007555 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7556 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007557 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7558 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007559 }
7560 }
Chris Lattner46b96052006-11-29 07:18:39 +00007561 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007562 case Instruction::ZExt:
7563 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007564 case Instruction::Trunc:
7565 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007566 // can safely replace it. Note that replacing it does not reduce the number
7567 // of casts in the input.
7568 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007569 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007570
Reid Spencer3da59db2006-11-27 01:05:10 +00007571 break;
7572 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007573 // TODO: Can handle more cases here.
7574 break;
7575 }
7576
7577 return false;
7578}
7579
7580/// EvaluateInDifferentType - Given an expression that
7581/// CanEvaluateInDifferentType returns true for, actually insert the code to
7582/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007583Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007584 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007585 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007586 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007587
7588 // Otherwise, it must be an instruction.
7589 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007590 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007591 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007592 case Instruction::Add:
7593 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007594 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007595 case Instruction::And:
7596 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007597 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007598 case Instruction::AShr:
7599 case Instruction::LShr:
7600 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007601 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007602 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007603 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007604 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007605 break;
7606 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007607 case Instruction::Trunc:
7608 case Instruction::ZExt:
7609 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007610 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007611 // just return the source. There's no need to insert it because it is not
7612 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007613 if (I->getOperand(0)->getType() == Ty)
7614 return I->getOperand(0);
7615
Chris Lattner951626b2007-08-02 06:11:14 +00007616 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007617 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007618 Ty, I->getName());
7619 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007620 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007621 // TODO: Can handle more cases here.
7622 assert(0 && "Unreachable!");
7623 break;
7624 }
7625
7626 return InsertNewInstBefore(Res, *I);
7627}
7628
Reid Spencer3da59db2006-11-27 01:05:10 +00007629/// @brief Implement the transforms common to all CastInst visitors.
7630Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007631 Value *Src = CI.getOperand(0);
7632
Dan Gohman23d9d272007-05-11 21:10:54 +00007633 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007634 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007635 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007636 if (Instruction::CastOps opc =
7637 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7638 // The first cast (CSrc) is eliminable so we need to fix up or replace
7639 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007640 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007641 }
7642 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007643
Reid Spencer3da59db2006-11-27 01:05:10 +00007644 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007645 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7646 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7647 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007648
7649 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007650 if (isa<PHINode>(Src))
7651 if (Instruction *NV = FoldOpIntoPhi(CI))
7652 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007653
Reid Spencer3da59db2006-11-27 01:05:10 +00007654 return 0;
7655}
7656
Chris Lattnerd3e28342007-04-27 17:44:50 +00007657/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7658Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7659 Value *Src = CI.getOperand(0);
7660
Chris Lattnerd3e28342007-04-27 17:44:50 +00007661 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007662 // If casting the result of a getelementptr instruction with no offset, turn
7663 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007664 if (GEP->hasAllZeroIndices()) {
7665 // Changing the cast operand is usually not a good idea but it is safe
7666 // here because the pointer operand is being replaced with another
7667 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007668 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007669 CI.setOperand(0, GEP->getOperand(0));
7670 return &CI;
7671 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007672
7673 // If the GEP has a single use, and the base pointer is a bitcast, and the
7674 // GEP computes a constant offset, see if we can convert these three
7675 // instructions into fewer. This typically happens with unions and other
7676 // non-type-safe code.
7677 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7678 if (GEP->hasAllConstantIndices()) {
7679 // We are guaranteed to get a constant from EmitGEPOffset.
7680 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7681 int64_t Offset = OffsetV->getSExtValue();
7682
7683 // Get the base pointer input of the bitcast, and the type it points to.
7684 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7685 const Type *GEPIdxTy =
7686 cast<PointerType>(OrigBase->getType())->getElementType();
7687 if (GEPIdxTy->isSized()) {
7688 SmallVector<Value*, 8> NewIndices;
7689
Chris Lattnerc42e2262007-05-05 01:59:31 +00007690 // Start with the index over the outer type. Note that the type size
7691 // might be zero (even if the offset isn't zero) if the indexed type
7692 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007693 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007694 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007695 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007696 FirstIdx = Offset/TySize;
7697 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007698
Chris Lattnerc42e2262007-05-05 01:59:31 +00007699 // Handle silly modulus not returning values values [0..TySize).
7700 if (Offset < 0) {
7701 --FirstIdx;
7702 Offset += TySize;
7703 assert(Offset >= 0);
7704 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007705 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007706 }
7707
7708 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007709
7710 // Index into the types. If we fail, set OrigBase to null.
7711 while (Offset) {
7712 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7713 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007714 if (Offset < (int64_t)SL->getSizeInBytes()) {
7715 unsigned Elt = SL->getElementContainingOffset(Offset);
7716 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007717
Chris Lattner6b6aef82007-05-15 00:16:00 +00007718 Offset -= SL->getElementOffset(Elt);
7719 GEPIdxTy = STy->getElementType(Elt);
7720 } else {
7721 // Otherwise, we can't index into this, bail out.
7722 Offset = 0;
7723 OrigBase = 0;
7724 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007725 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7726 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007727 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007728 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7729 Offset %= EltSize;
7730 } else {
7731 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7732 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007733 GEPIdxTy = STy->getElementType();
7734 } else {
7735 // Otherwise, we can't index into this, bail out.
7736 Offset = 0;
7737 OrigBase = 0;
7738 }
7739 }
7740 if (OrigBase) {
7741 // If we were able to index down into an element, create the GEP
7742 // and bitcast the result. This eliminates one bitcast, potentially
7743 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007744 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7745 NewIndices.begin(),
7746 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007747 InsertNewInstBefore(NGEP, CI);
7748 NGEP->takeName(GEP);
7749
Chris Lattner9bc14642007-04-28 00:57:34 +00007750 if (isa<BitCastInst>(CI))
7751 return new BitCastInst(NGEP, CI.getType());
7752 assert(isa<PtrToIntInst>(CI));
7753 return new PtrToIntInst(NGEP, CI.getType());
7754 }
7755 }
7756 }
7757 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007758 }
7759
7760 return commonCastTransforms(CI);
7761}
7762
7763
7764
Chris Lattnerc739cd62007-03-03 05:27:34 +00007765/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7766/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007767/// cases.
7768/// @brief Implement the transforms common to CastInst with integer operands
7769Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7770 if (Instruction *Result = commonCastTransforms(CI))
7771 return Result;
7772
7773 Value *Src = CI.getOperand(0);
7774 const Type *SrcTy = Src->getType();
7775 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007776 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7777 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007778
Reid Spencer3da59db2006-11-27 01:05:10 +00007779 // See if we can simplify any instructions used by the LHS whose sole
7780 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007781 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7782 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007783 KnownZero, KnownOne))
7784 return &CI;
7785
7786 // If the source isn't an instruction or has more than one use then we
7787 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007788 Instruction *SrcI = dyn_cast<Instruction>(Src);
7789 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007790 return 0;
7791
Chris Lattnerc739cd62007-03-03 05:27:34 +00007792 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007793 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007794 if (!isa<BitCastInst>(CI) &&
7795 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007796 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007797 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007798 // eliminates the cast, so it is always a win. If this is a zero-extension,
7799 // we need to do an AND to maintain the clear top-part of the computation,
7800 // so we require that the input have eliminated at least one cast. If this
7801 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007802 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007803 bool DoXForm;
7804 switch (CI.getOpcode()) {
7805 default:
7806 // All the others use floating point so we shouldn't actually
7807 // get here because of the check above.
7808 assert(0 && "Unknown cast type");
7809 case Instruction::Trunc:
7810 DoXForm = true;
7811 break;
7812 case Instruction::ZExt:
7813 DoXForm = NumCastsRemoved >= 1;
7814 break;
7815 case Instruction::SExt:
7816 DoXForm = NumCastsRemoved >= 2;
7817 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007818 }
7819
7820 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007821 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7822 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007823 assert(Res->getType() == DestTy);
7824 switch (CI.getOpcode()) {
7825 default: assert(0 && "Unknown cast type!");
7826 case Instruction::Trunc:
7827 case Instruction::BitCast:
7828 // Just replace this cast with the result.
7829 return ReplaceInstUsesWith(CI, Res);
7830 case Instruction::ZExt: {
7831 // We need to emit an AND to clear the high bits.
7832 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007833 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7834 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007835 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007836 }
7837 case Instruction::SExt:
7838 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007839 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007840 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7841 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007842 }
7843 }
7844 }
7845
7846 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7847 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7848
7849 switch (SrcI->getOpcode()) {
7850 case Instruction::Add:
7851 case Instruction::Mul:
7852 case Instruction::And:
7853 case Instruction::Or:
7854 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007855 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007856 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7857 // Don't insert two casts if they cannot be eliminated. We allow
7858 // two casts to be inserted if the sizes are the same. This could
7859 // only be converting signedness, which is a noop.
7860 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007861 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7862 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007863 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007864 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7865 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007866 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007867 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007868 }
7869 }
7870
7871 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7872 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7873 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007874 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007875 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007876 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007877 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007878 }
7879 break;
7880 case Instruction::SDiv:
7881 case Instruction::UDiv:
7882 case Instruction::SRem:
7883 case Instruction::URem:
7884 // If we are just changing the sign, rewrite.
7885 if (DestBitSize == SrcBitSize) {
7886 // Don't insert two casts if they cannot be eliminated. We allow
7887 // two casts to be inserted if the sizes are the same. This could
7888 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007889 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7890 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007891 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7892 Op0, DestTy, SrcI);
7893 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7894 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007895 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007896 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7897 }
7898 }
7899 break;
7900
7901 case Instruction::Shl:
7902 // Allow changing the sign of the source operand. Do not allow
7903 // changing the size of the shift, UNLESS the shift amount is a
7904 // constant. We must not change variable sized shifts to a smaller
7905 // size, because it is undefined to shift more bits out than exist
7906 // in the value.
7907 if (DestBitSize == SrcBitSize ||
7908 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007909 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7910 Instruction::BitCast : Instruction::Trunc);
7911 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007912 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007913 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007914 }
7915 break;
7916 case Instruction::AShr:
7917 // If this is a signed shr, and if all bits shifted in are about to be
7918 // truncated off, turn it into an unsigned shr to allow greater
7919 // simplifications.
7920 if (DestBitSize < SrcBitSize &&
7921 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007922 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007923 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7924 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007925 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007926 }
7927 }
7928 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007929 }
7930 return 0;
7931}
7932
Chris Lattner8a9f5712007-04-11 06:57:46 +00007933Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007934 if (Instruction *Result = commonIntCastTransforms(CI))
7935 return Result;
7936
7937 Value *Src = CI.getOperand(0);
7938 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007939 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7940 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007941
7942 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7943 switch (SrcI->getOpcode()) {
7944 default: break;
7945 case Instruction::LShr:
7946 // We can shrink lshr to something smaller if we know the bits shifted in
7947 // are already zeros.
7948 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007949 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007950
7951 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007952 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007953 Value* SrcIOp0 = SrcI->getOperand(0);
7954 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007955 if (ShAmt >= DestBitWidth) // All zeros.
7956 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7957
7958 // Okay, we can shrink this. Truncate the input, then return a new
7959 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007960 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7961 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7962 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007963 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007964 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007965 } else { // This is a variable shr.
7966
7967 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7968 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7969 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007970 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007971 Value *One = ConstantInt::get(SrcI->getType(), 1);
7972
Reid Spencer832254e2007-02-02 02:16:23 +00007973 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007974 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007975 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007976 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007977 SrcI->getOperand(0),
7978 "tmp"), CI);
7979 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007980 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007981 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007982 }
7983 break;
7984 }
7985 }
7986
7987 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007988}
7989
Evan Chengb98a10e2008-03-24 00:21:34 +00007990/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7991/// in order to eliminate the icmp.
7992Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7993 bool DoXform) {
7994 // If we are just checking for a icmp eq of a single bit and zext'ing it
7995 // to an integer, then shift the bit to the appropriate place and then
7996 // cast to integer to avoid the comparison.
7997 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7998 const APInt &Op1CV = Op1C->getValue();
7999
8000 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8001 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8002 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8003 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8004 if (!DoXform) return ICI;
8005
8006 Value *In = ICI->getOperand(0);
8007 Value *Sh = ConstantInt::get(In->getType(),
8008 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008009 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008010 In->getName()+".lobit"),
8011 CI);
8012 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008013 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008014 false/*ZExt*/, "tmp", &CI);
8015
8016 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8017 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008018 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008019 In->getName()+".not"),
8020 CI);
8021 }
8022
8023 return ReplaceInstUsesWith(CI, In);
8024 }
8025
8026
8027
8028 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8029 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8030 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8031 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8032 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8033 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8034 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8035 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8036 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8037 // This only works for EQ and NE
8038 ICI->isEquality()) {
8039 // If Op1C some other power of two, convert:
8040 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8041 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8042 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8043 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8044
8045 APInt KnownZeroMask(~KnownZero);
8046 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8047 if (!DoXform) return ICI;
8048
8049 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8050 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8051 // (X&4) == 2 --> false
8052 // (X&4) != 2 --> true
8053 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8054 Res = ConstantExpr::getZExt(Res, CI.getType());
8055 return ReplaceInstUsesWith(CI, Res);
8056 }
8057
8058 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8059 Value *In = ICI->getOperand(0);
8060 if (ShiftAmt) {
8061 // Perform a logical shr by shiftamt.
8062 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008063 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008064 ConstantInt::get(In->getType(), ShiftAmt),
8065 In->getName()+".lobit"), CI);
8066 }
8067
8068 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8069 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008070 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008071 InsertNewInstBefore(cast<Instruction>(In), CI);
8072 }
8073
8074 if (CI.getType() == In->getType())
8075 return ReplaceInstUsesWith(CI, In);
8076 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008077 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008078 }
8079 }
8080 }
8081
8082 return 0;
8083}
8084
Chris Lattner8a9f5712007-04-11 06:57:46 +00008085Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008086 // If one of the common conversion will work ..
8087 if (Instruction *Result = commonIntCastTransforms(CI))
8088 return Result;
8089
8090 Value *Src = CI.getOperand(0);
8091
8092 // If this is a cast of a cast
8093 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008094 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8095 // types and if the sizes are just right we can convert this into a logical
8096 // 'and' which will be much cheaper than the pair of casts.
8097 if (isa<TruncInst>(CSrc)) {
8098 // Get the sizes of the types involved
8099 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008100 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8101 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8102 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008103 // If we're actually extending zero bits and the trunc is a no-op
8104 if (MidSize < DstSize && SrcSize == DstSize) {
8105 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008106 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008107 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008108 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008109 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008110 // Unfortunately, if the type changed, we need to cast it back.
8111 if (And->getType() != CI.getType()) {
8112 And->setName(CSrc->getName()+".mask");
8113 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008114 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008115 }
8116 return And;
8117 }
8118 }
8119 }
8120
Evan Chengb98a10e2008-03-24 00:21:34 +00008121 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8122 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008123
Evan Chengb98a10e2008-03-24 00:21:34 +00008124 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8125 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8126 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8127 // of the (zext icmp) will be transformed.
8128 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8129 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8130 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8131 (transformZExtICmp(LHS, CI, false) ||
8132 transformZExtICmp(RHS, CI, false))) {
8133 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8134 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008135 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008136 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008137 }
8138
Reid Spencer3da59db2006-11-27 01:05:10 +00008139 return 0;
8140}
8141
Chris Lattner8a9f5712007-04-11 06:57:46 +00008142Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008143 if (Instruction *I = commonIntCastTransforms(CI))
8144 return I;
8145
Chris Lattner8a9f5712007-04-11 06:57:46 +00008146 Value *Src = CI.getOperand(0);
8147
8148 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8149 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8150 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8151 // If we are just checking for a icmp eq of a single bit and zext'ing it
8152 // to an integer, then shift the bit to the appropriate place and then
8153 // cast to integer to avoid the comparison.
8154 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8155 const APInt &Op1CV = Op1C->getValue();
8156
8157 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8158 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8159 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8160 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8161 Value *In = ICI->getOperand(0);
8162 Value *Sh = ConstantInt::get(In->getType(),
8163 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008164 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008165 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008166 CI);
8167 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008168 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008169 true/*SExt*/, "tmp", &CI);
8170
8171 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008172 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008173 In->getName()+".not"), CI);
8174
8175 return ReplaceInstUsesWith(CI, In);
8176 }
8177 }
8178 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008179
8180 // See if the value being truncated is already sign extended. If so, just
8181 // eliminate the trunc/sext pair.
8182 if (getOpcode(Src) == Instruction::Trunc) {
8183 Value *Op = cast<User>(Src)->getOperand(0);
8184 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8185 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8186 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8187 unsigned NumSignBits = ComputeNumSignBits(Op);
8188
8189 if (OpBits == DestBits) {
8190 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8191 // bits, it is already ready.
8192 if (NumSignBits > DestBits-MidBits)
8193 return ReplaceInstUsesWith(CI, Op);
8194 } else if (OpBits < DestBits) {
8195 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8196 // bits, just sext from i32.
8197 if (NumSignBits > OpBits-MidBits)
8198 return new SExtInst(Op, CI.getType(), "tmp");
8199 } else {
8200 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8201 // bits, just truncate to i32.
8202 if (NumSignBits > OpBits-MidBits)
8203 return new TruncInst(Op, CI.getType(), "tmp");
8204 }
8205 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008206
Chris Lattnerba417832007-04-11 06:12:58 +00008207 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008208}
8209
Chris Lattnerb7530652008-01-27 05:29:54 +00008210/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8211/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008212static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008213 APFloat F = CFP->getValueAPF();
8214 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008215 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008216 return 0;
8217}
8218
8219/// LookThroughFPExtensions - If this is an fp extension instruction, look
8220/// through it until we get the source value.
8221static Value *LookThroughFPExtensions(Value *V) {
8222 if (Instruction *I = dyn_cast<Instruction>(V))
8223 if (I->getOpcode() == Instruction::FPExt)
8224 return LookThroughFPExtensions(I->getOperand(0));
8225
8226 // If this value is a constant, return the constant in the smallest FP type
8227 // that can accurately represent it. This allows us to turn
8228 // (float)((double)X+2.0) into x+2.0f.
8229 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8230 if (CFP->getType() == Type::PPC_FP128Ty)
8231 return V; // No constant folding of this.
8232 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008233 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008234 return V;
8235 if (CFP->getType() == Type::DoubleTy)
8236 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008237 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008238 return V;
8239 // Don't try to shrink to various long double types.
8240 }
8241
8242 return V;
8243}
8244
8245Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8246 if (Instruction *I = commonCastTransforms(CI))
8247 return I;
8248
8249 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8250 // smaller than the destination type, we can eliminate the truncate by doing
8251 // the add as the smaller type. This applies to add/sub/mul/div as well as
8252 // many builtins (sqrt, etc).
8253 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8254 if (OpI && OpI->hasOneUse()) {
8255 switch (OpI->getOpcode()) {
8256 default: break;
8257 case Instruction::Add:
8258 case Instruction::Sub:
8259 case Instruction::Mul:
8260 case Instruction::FDiv:
8261 case Instruction::FRem:
8262 const Type *SrcTy = OpI->getType();
8263 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8264 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8265 if (LHSTrunc->getType() != SrcTy &&
8266 RHSTrunc->getType() != SrcTy) {
8267 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8268 // If the source types were both smaller than the destination type of
8269 // the cast, do this xform.
8270 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8271 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8272 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8273 CI.getType(), CI);
8274 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8275 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008276 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008277 }
8278 }
8279 break;
8280 }
8281 }
8282 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008283}
8284
8285Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8286 return commonCastTransforms(CI);
8287}
8288
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008289Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8290 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8291 // mantissa to accurately represent all values of X. For example, do not
8292 // do this with i64->float->i64.
8293 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8294 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8295 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008296 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008297 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8298
8299 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008300}
8301
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008302Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8303 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8304 // mantissa to accurately represent all values of X. For example, do not
8305 // do this with i64->float->i64.
8306 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8307 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8308 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008309 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008310 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8311
8312 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008313}
8314
8315Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8316 return commonCastTransforms(CI);
8317}
8318
8319Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8320 return commonCastTransforms(CI);
8321}
8322
8323Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008324 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008325}
8326
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008327Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8328 if (Instruction *I = commonCastTransforms(CI))
8329 return I;
8330
8331 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8332 if (!DestPointee->isSized()) return 0;
8333
8334 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8335 ConstantInt *Cst;
8336 Value *X;
8337 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8338 m_ConstantInt(Cst)))) {
8339 // If the source and destination operands have the same type, see if this
8340 // is a single-index GEP.
8341 if (X->getType() == CI.getType()) {
8342 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008343 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008344
8345 // Convert the constant to intptr type.
8346 APInt Offset = Cst->getValue();
8347 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8348
8349 // If Offset is evenly divisible by Size, we can do this xform.
8350 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8351 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008352 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008353 }
8354 }
8355 // TODO: Could handle other cases, e.g. where add is indexing into field of
8356 // struct etc.
8357 } else if (CI.getOperand(0)->hasOneUse() &&
8358 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8359 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8360 // "inttoptr+GEP" instead of "add+intptr".
8361
8362 // Get the size of the pointee type.
8363 uint64_t Size = TD->getABITypeSize(DestPointee);
8364
8365 // Convert the constant to intptr type.
8366 APInt Offset = Cst->getValue();
8367 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8368
8369 // If Offset is evenly divisible by Size, we can do this xform.
8370 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8371 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8372
8373 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8374 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008375 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008376 }
8377 }
8378 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008379}
8380
Chris Lattnerd3e28342007-04-27 17:44:50 +00008381Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 // If the operands are integer typed then apply the integer transforms,
8383 // otherwise just apply the common ones.
8384 Value *Src = CI.getOperand(0);
8385 const Type *SrcTy = Src->getType();
8386 const Type *DestTy = CI.getType();
8387
Chris Lattner42a75512007-01-15 02:27:26 +00008388 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008389 if (Instruction *Result = commonIntCastTransforms(CI))
8390 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008391 } else if (isa<PointerType>(SrcTy)) {
8392 if (Instruction *I = commonPointerCastTransforms(CI))
8393 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008394 } else {
8395 if (Instruction *Result = commonCastTransforms(CI))
8396 return Result;
8397 }
8398
8399
8400 // Get rid of casts from one type to the same type. These are useless and can
8401 // be replaced by the operand.
8402 if (DestTy == Src->getType())
8403 return ReplaceInstUsesWith(CI, Src);
8404
Reid Spencer3da59db2006-11-27 01:05:10 +00008405 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008406 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8407 const Type *DstElTy = DstPTy->getElementType();
8408 const Type *SrcElTy = SrcPTy->getElementType();
8409
Nate Begeman83ad90a2008-03-31 00:22:16 +00008410 // If the address spaces don't match, don't eliminate the bitcast, which is
8411 // required for changing types.
8412 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8413 return 0;
8414
Chris Lattnerd3e28342007-04-27 17:44:50 +00008415 // If we are casting a malloc or alloca to a pointer to a type of the same
8416 // size, rewrite the allocation instruction to allocate the "right" type.
8417 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8418 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8419 return V;
8420
Chris Lattnerd717c182007-05-05 22:32:24 +00008421 // If the source and destination are pointers, and this cast is equivalent
8422 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008423 // This can enhance SROA and other transforms that want type-safe pointers.
8424 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8425 unsigned NumZeros = 0;
8426 while (SrcElTy != DstElTy &&
8427 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8428 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8429 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8430 ++NumZeros;
8431 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008432
Chris Lattnerd3e28342007-04-27 17:44:50 +00008433 // If we found a path from the src to dest, create the getelementptr now.
8434 if (SrcElTy == DstElTy) {
8435 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008436 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8437 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008438 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008439 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008440
Reid Spencer3da59db2006-11-27 01:05:10 +00008441 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8442 if (SVI->hasOneUse()) {
8443 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8444 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008445 if (isa<VectorType>(DestTy) &&
8446 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008447 SVI->getType()->getNumElements()) {
8448 CastInst *Tmp;
8449 // If either of the operands is a cast from CI.getType(), then
8450 // evaluating the shuffle in the casted destination's type will allow
8451 // us to eliminate at least one cast.
8452 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8453 Tmp->getOperand(0)->getType() == DestTy) ||
8454 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8455 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008456 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8457 SVI->getOperand(0), DestTy, &CI);
8458 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8459 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008460 // Return a new shuffle vector. Use the same element ID's, as we
8461 // know the vector types match #elts.
8462 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008463 }
8464 }
8465 }
8466 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008467 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008468}
8469
Chris Lattnere576b912004-04-09 23:46:01 +00008470/// GetSelectFoldableOperands - We want to turn code that looks like this:
8471/// %C = or %A, %B
8472/// %D = select %cond, %C, %A
8473/// into:
8474/// %C = select %cond, %B, 0
8475/// %D = or %A, %C
8476///
8477/// Assuming that the specified instruction is an operand to the select, return
8478/// a bitmask indicating which operands of this instruction are foldable if they
8479/// equal the other incoming value of the select.
8480///
8481static unsigned GetSelectFoldableOperands(Instruction *I) {
8482 switch (I->getOpcode()) {
8483 case Instruction::Add:
8484 case Instruction::Mul:
8485 case Instruction::And:
8486 case Instruction::Or:
8487 case Instruction::Xor:
8488 return 3; // Can fold through either operand.
8489 case Instruction::Sub: // Can only fold on the amount subtracted.
8490 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008491 case Instruction::LShr:
8492 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008493 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008494 default:
8495 return 0; // Cannot fold
8496 }
8497}
8498
8499/// GetSelectFoldableConstant - For the same transformation as the previous
8500/// function, return the identity constant that goes into the select.
8501static Constant *GetSelectFoldableConstant(Instruction *I) {
8502 switch (I->getOpcode()) {
8503 default: assert(0 && "This cannot happen!"); abort();
8504 case Instruction::Add:
8505 case Instruction::Sub:
8506 case Instruction::Or:
8507 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008508 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008509 case Instruction::LShr:
8510 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008511 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008512 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008513 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008514 case Instruction::Mul:
8515 return ConstantInt::get(I->getType(), 1);
8516 }
8517}
8518
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008519/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8520/// have the same opcode and only one use each. Try to simplify this.
8521Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8522 Instruction *FI) {
8523 if (TI->getNumOperands() == 1) {
8524 // If this is a non-volatile load or a cast from the same type,
8525 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008526 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008527 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8528 return 0;
8529 } else {
8530 return 0; // unknown unary op.
8531 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008532
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008533 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008534 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8535 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008536 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008537 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008538 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008539 }
8540
Reid Spencer832254e2007-02-02 02:16:23 +00008541 // Only handle binary operators here.
8542 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008543 return 0;
8544
8545 // Figure out if the operations have any operands in common.
8546 Value *MatchOp, *OtherOpT, *OtherOpF;
8547 bool MatchIsOpZero;
8548 if (TI->getOperand(0) == FI->getOperand(0)) {
8549 MatchOp = TI->getOperand(0);
8550 OtherOpT = TI->getOperand(1);
8551 OtherOpF = FI->getOperand(1);
8552 MatchIsOpZero = true;
8553 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8554 MatchOp = TI->getOperand(1);
8555 OtherOpT = TI->getOperand(0);
8556 OtherOpF = FI->getOperand(0);
8557 MatchIsOpZero = false;
8558 } else if (!TI->isCommutative()) {
8559 return 0;
8560 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8561 MatchOp = TI->getOperand(0);
8562 OtherOpT = TI->getOperand(1);
8563 OtherOpF = FI->getOperand(0);
8564 MatchIsOpZero = true;
8565 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8566 MatchOp = TI->getOperand(1);
8567 OtherOpT = TI->getOperand(0);
8568 OtherOpF = FI->getOperand(1);
8569 MatchIsOpZero = true;
8570 } else {
8571 return 0;
8572 }
8573
8574 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008575 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8576 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008577 InsertNewInstBefore(NewSI, SI);
8578
8579 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8580 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008581 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008582 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008583 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008584 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008585 assert(0 && "Shouldn't get here");
8586 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008587}
8588
Chris Lattner3d69f462004-03-12 05:52:32 +00008589Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008590 Value *CondVal = SI.getCondition();
8591 Value *TrueVal = SI.getTrueValue();
8592 Value *FalseVal = SI.getFalseValue();
8593
8594 // select true, X, Y -> X
8595 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008596 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008597 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008598
8599 // select C, X, X -> X
8600 if (TrueVal == FalseVal)
8601 return ReplaceInstUsesWith(SI, TrueVal);
8602
Chris Lattnere87597f2004-10-16 18:11:37 +00008603 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8604 return ReplaceInstUsesWith(SI, FalseVal);
8605 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8606 return ReplaceInstUsesWith(SI, TrueVal);
8607 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8608 if (isa<Constant>(TrueVal))
8609 return ReplaceInstUsesWith(SI, TrueVal);
8610 else
8611 return ReplaceInstUsesWith(SI, FalseVal);
8612 }
8613
Reid Spencer4fe16d62007-01-11 18:21:29 +00008614 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008615 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008616 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008617 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008618 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008619 } else {
8620 // Change: A = select B, false, C --> A = and !B, C
8621 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008622 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008623 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008624 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008625 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008626 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008627 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008628 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008629 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008630 } else {
8631 // Change: A = select B, C, true --> A = or !B, C
8632 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008633 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008634 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008635 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008636 }
8637 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008638
8639 // select a, b, a -> a&b
8640 // select a, a, b -> a|b
8641 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008642 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008643 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008644 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008645 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008646
Chris Lattner2eefe512004-04-09 19:05:30 +00008647 // Selecting between two integer constants?
8648 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8649 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008650 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008651 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008652 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008653 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008654 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008655 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008656 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008657 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008658 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008659 }
Chris Lattnerba417832007-04-11 06:12:58 +00008660
8661 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008662
Reid Spencere4d87aa2006-12-23 06:05:41 +00008663 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008664
Reid Spencere4d87aa2006-12-23 06:05:41 +00008665 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008666 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008667 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008668 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008669 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008670 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008671 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008672 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008673 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008674 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008675 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008676 InsertNewInstBefore(SRA, SI);
8677
Reid Spencer3da59db2006-11-27 01:05:10 +00008678 // Finally, convert to the type of the select RHS. We figure out
8679 // if this requires a SExt, Trunc or BitCast based on the sizes.
8680 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008681 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8682 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008683 if (SRASize < SISize)
8684 opc = Instruction::SExt;
8685 else if (SRASize > SISize)
8686 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008687 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008688 }
8689 }
8690
8691
8692 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008693 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008694 // non-constant value, eliminate this whole mess. This corresponds to
8695 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008696 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008697 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008698 cast<Constant>(IC->getOperand(1))->isNullValue())
8699 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8700 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008701 isa<ConstantInt>(ICA->getOperand(1)) &&
8702 (ICA->getOperand(1) == TrueValC ||
8703 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008704 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8705 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008706 // know whether we have a icmp_ne or icmp_eq and whether the
8707 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008708 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008709 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008710 Value *V = ICA;
8711 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008712 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008713 Instruction::Xor, V, ICA->getOperand(1)), SI);
8714 return ReplaceInstUsesWith(SI, V);
8715 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008716 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008717 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008718
8719 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008720 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8721 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008722 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008723 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8724 // This is not safe in general for floating point:
8725 // consider X== -0, Y== +0.
8726 // It becomes safe if either operand is a nonzero constant.
8727 ConstantFP *CFPt, *CFPf;
8728 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8729 !CFPt->getValueAPF().isZero()) ||
8730 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8731 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008732 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008733 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008734 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008735 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008736 return ReplaceInstUsesWith(SI, TrueVal);
8737 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8738
Reid Spencere4d87aa2006-12-23 06:05:41 +00008739 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008740 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008741 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8742 // This is not safe in general for floating point:
8743 // consider X== -0, Y== +0.
8744 // It becomes safe if either operand is a nonzero constant.
8745 ConstantFP *CFPt, *CFPf;
8746 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8747 !CFPt->getValueAPF().isZero()) ||
8748 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8749 !CFPf->getValueAPF().isZero()))
8750 return ReplaceInstUsesWith(SI, FalseVal);
8751 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008752 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008753 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8754 return ReplaceInstUsesWith(SI, TrueVal);
8755 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8756 }
8757 }
8758
8759 // See if we are selecting two values based on a comparison of the two values.
8760 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8761 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8762 // Transform (X == Y) ? X : Y -> Y
8763 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8764 return ReplaceInstUsesWith(SI, FalseVal);
8765 // Transform (X != Y) ? X : Y -> X
8766 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8767 return ReplaceInstUsesWith(SI, TrueVal);
8768 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8769
8770 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8771 // Transform (X == Y) ? Y : X -> X
8772 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8773 return ReplaceInstUsesWith(SI, FalseVal);
8774 // Transform (X != Y) ? Y : X -> Y
8775 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008776 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008777 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8778 }
8779 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008780
Chris Lattner87875da2005-01-13 22:52:24 +00008781 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8782 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8783 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008784 Instruction *AddOp = 0, *SubOp = 0;
8785
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008786 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8787 if (TI->getOpcode() == FI->getOpcode())
8788 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8789 return IV;
8790
8791 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8792 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008793 if (TI->getOpcode() == Instruction::Sub &&
8794 FI->getOpcode() == Instruction::Add) {
8795 AddOp = FI; SubOp = TI;
8796 } else if (FI->getOpcode() == Instruction::Sub &&
8797 TI->getOpcode() == Instruction::Add) {
8798 AddOp = TI; SubOp = FI;
8799 }
8800
8801 if (AddOp) {
8802 Value *OtherAddOp = 0;
8803 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8804 OtherAddOp = AddOp->getOperand(1);
8805 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8806 OtherAddOp = AddOp->getOperand(0);
8807 }
8808
8809 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008810 // So at this point we know we have (Y -> OtherAddOp):
8811 // select C, (add X, Y), (sub X, Z)
8812 Value *NegVal; // Compute -Z
8813 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8814 NegVal = ConstantExpr::getNeg(C);
8815 } else {
8816 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008817 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008818 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008819
8820 Value *NewTrueOp = OtherAddOp;
8821 Value *NewFalseOp = NegVal;
8822 if (AddOp != TI)
8823 std::swap(NewTrueOp, NewFalseOp);
8824 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008825 SelectInst::Create(CondVal, NewTrueOp,
8826 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008827
8828 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008829 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008830 }
8831 }
8832 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008833
Chris Lattnere576b912004-04-09 23:46:01 +00008834 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008835 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008836 // See the comment above GetSelectFoldableOperands for a description of the
8837 // transformation we are doing here.
8838 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8839 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8840 !isa<Constant>(FalseVal))
8841 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8842 unsigned OpToFold = 0;
8843 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8844 OpToFold = 1;
8845 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8846 OpToFold = 2;
8847 }
8848
8849 if (OpToFold) {
8850 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008851 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008852 SelectInst::Create(SI.getCondition(),
8853 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008854 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008855 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008856 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008857 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008858 else {
8859 assert(0 && "Unknown instruction!!");
8860 }
8861 }
8862 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008863
Chris Lattnere576b912004-04-09 23:46:01 +00008864 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8865 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8866 !isa<Constant>(TrueVal))
8867 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8868 unsigned OpToFold = 0;
8869 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8870 OpToFold = 1;
8871 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8872 OpToFold = 2;
8873 }
8874
8875 if (OpToFold) {
8876 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008877 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008878 SelectInst::Create(SI.getCondition(), C,
8879 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008880 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008881 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008883 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008884 else
Chris Lattnere576b912004-04-09 23:46:01 +00008885 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008886 }
8887 }
8888 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008889
8890 if (BinaryOperator::isNot(CondVal)) {
8891 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8892 SI.setOperand(1, FalseVal);
8893 SI.setOperand(2, TrueVal);
8894 return &SI;
8895 }
8896
Chris Lattner3d69f462004-03-12 05:52:32 +00008897 return 0;
8898}
8899
Dan Gohmaneee962e2008-04-10 18:43:06 +00008900/// EnforceKnownAlignment - If the specified pointer points to an object that
8901/// we control, modify the object's alignment to PrefAlign. This isn't
8902/// often possible though. If alignment is important, a more reliable approach
8903/// is to simply align all global variables and allocation instructions to
8904/// their preferred alignment from the beginning.
8905///
8906static unsigned EnforceKnownAlignment(Value *V,
8907 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008908
Dan Gohmaneee962e2008-04-10 18:43:06 +00008909 User *U = dyn_cast<User>(V);
8910 if (!U) return Align;
8911
8912 switch (getOpcode(U)) {
8913 default: break;
8914 case Instruction::BitCast:
8915 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8916 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008917 // If all indexes are zero, it is just the alignment of the base pointer.
8918 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008919 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8920 if (!isa<Constant>(U->getOperand(i)) ||
8921 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008922 AllZeroOperands = false;
8923 break;
8924 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008925
8926 if (AllZeroOperands) {
8927 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008928 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008929 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008930 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008931 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008932 }
8933
8934 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8935 // If there is a large requested alignment and we can, bump up the alignment
8936 // of the global.
8937 if (!GV->isDeclaration()) {
8938 GV->setAlignment(PrefAlign);
8939 Align = PrefAlign;
8940 }
8941 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8942 // If there is a requested alignment and if this is an alloca, round up. We
8943 // don't do this for malloc, because some systems can't respect the request.
8944 if (isa<AllocaInst>(AI)) {
8945 AI->setAlignment(PrefAlign);
8946 Align = PrefAlign;
8947 }
8948 }
8949
8950 return Align;
8951}
8952
8953/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8954/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8955/// and it is more than the alignment of the ultimate object, see if we can
8956/// increase the alignment of the ultimate object, making this check succeed.
8957unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8958 unsigned PrefAlign) {
8959 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8960 sizeof(PrefAlign) * CHAR_BIT;
8961 APInt Mask = APInt::getAllOnesValue(BitWidth);
8962 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8963 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8964 unsigned TrailZ = KnownZero.countTrailingOnes();
8965 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8966
8967 if (PrefAlign > Align)
8968 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8969
8970 // We don't need to make any adjustment.
8971 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008972}
8973
Chris Lattnerf497b022008-01-13 23:50:23 +00008974Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008975 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8976 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008977 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8978 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8979
8980 if (CopyAlign < MinAlign) {
8981 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8982 return MI;
8983 }
8984
8985 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8986 // load/store.
8987 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8988 if (MemOpLength == 0) return 0;
8989
Chris Lattner37ac6082008-01-14 00:28:35 +00008990 // Source and destination pointer types are always "i8*" for intrinsic. See
8991 // if the size is something we can handle with a single primitive load/store.
8992 // A single load+store correctly handles overlapping memory in the memmove
8993 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008994 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008995 if (Size == 0) return MI; // Delete this mem transfer.
8996
8997 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008998 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008999
Chris Lattner37ac6082008-01-14 00:28:35 +00009000 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00009001 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009002
9003 // Memcpy forces the use of i8* for the source and destination. That means
9004 // that if you're using memcpy to move one double around, you'll get a cast
9005 // from double* to i8*. We'd much rather use a double load+store rather than
9006 // an i64 load+store, here because this improves the odds that the source or
9007 // dest address will be promotable. See if we can find a better type than the
9008 // integer datatype.
9009 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9010 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9011 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9012 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9013 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009014 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009015 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9016 if (STy->getNumElements() == 1)
9017 SrcETy = STy->getElementType(0);
9018 else
9019 break;
9020 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9021 if (ATy->getNumElements() == 1)
9022 SrcETy = ATy->getElementType();
9023 else
9024 break;
9025 } else
9026 break;
9027 }
9028
Dan Gohman8f8e2692008-05-23 01:52:21 +00009029 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009030 NewPtrTy = PointerType::getUnqual(SrcETy);
9031 }
9032 }
9033
9034
Chris Lattnerf497b022008-01-13 23:50:23 +00009035 // If the memcpy/memmove provides better alignment info than we can
9036 // infer, use it.
9037 SrcAlign = std::max(SrcAlign, CopyAlign);
9038 DstAlign = std::max(DstAlign, CopyAlign);
9039
9040 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9041 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009042 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9043 InsertNewInstBefore(L, *MI);
9044 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9045
9046 // Set the size of the copy to 0, it will be deleted on the next iteration.
9047 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9048 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009049}
Chris Lattner3d69f462004-03-12 05:52:32 +00009050
Chris Lattner69ea9d22008-04-30 06:39:11 +00009051Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9052 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9053 if (MI->getAlignment()->getZExtValue() < Alignment) {
9054 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9055 return MI;
9056 }
9057
9058 // Extract the length and alignment and fill if they are constant.
9059 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9060 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9061 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9062 return 0;
9063 uint64_t Len = LenC->getZExtValue();
9064 Alignment = MI->getAlignment()->getZExtValue();
9065
9066 // If the length is zero, this is a no-op
9067 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9068
9069 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9070 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9071 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9072
9073 Value *Dest = MI->getDest();
9074 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9075
9076 // Alignment 0 is identity for alignment 1 for memset, but not store.
9077 if (Alignment == 0) Alignment = 1;
9078
9079 // Extract the fill value and store.
9080 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9081 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9082 Alignment), *MI);
9083
9084 // Set the size of the copy to 0, it will be deleted on the next iteration.
9085 MI->setLength(Constant::getNullValue(LenC->getType()));
9086 return MI;
9087 }
9088
9089 return 0;
9090}
9091
9092
Chris Lattner8b0ea312006-01-13 20:11:04 +00009093/// visitCallInst - CallInst simplification. This mostly only handles folding
9094/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9095/// the heavy lifting.
9096///
Chris Lattner9fe38862003-06-19 17:00:31 +00009097Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009098 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9099 if (!II) return visitCallSite(&CI);
9100
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009101 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9102 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009103 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009104 bool Changed = false;
9105
9106 // memmove/cpy/set of zero bytes is a noop.
9107 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9108 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9109
Chris Lattner35b9e482004-10-12 04:52:52 +00009110 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009111 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009112 // Replace the instruction with just byte operations. We would
9113 // transform other cases to loads/stores, but we don't know if
9114 // alignment is sufficient.
9115 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009116 }
9117
Chris Lattner35b9e482004-10-12 04:52:52 +00009118 // If we have a memmove and the source operation is a constant global,
9119 // then the source and dest pointers can't alias, so we can change this
9120 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009121 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009122 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9123 if (GVSrc->isConstant()) {
9124 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009125 Intrinsic::ID MemCpyID;
9126 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9127 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009128 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009129 MemCpyID = Intrinsic::memcpy_i64;
9130 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009131 Changed = true;
9132 }
Chris Lattner95a959d2006-03-06 20:18:44 +00009133 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009134
Chris Lattner95a959d2006-03-06 20:18:44 +00009135 // If we can determine a pointer alignment that is bigger than currently
9136 // set, update the alignment.
9137 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009138 if (Instruction *I = SimplifyMemTransfer(MI))
9139 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009140 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9141 if (Instruction *I = SimplifyMemSet(MSI))
9142 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009143 }
9144
Chris Lattner8b0ea312006-01-13 20:11:04 +00009145 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009146 } else {
9147 switch (II->getIntrinsicID()) {
9148 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009149 case Intrinsic::ppc_altivec_lvx:
9150 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009151 case Intrinsic::x86_sse_loadu_ps:
9152 case Intrinsic::x86_sse2_loadu_pd:
9153 case Intrinsic::x86_sse2_loadu_dq:
9154 // Turn PPC lvx -> load if the pointer is known aligned.
9155 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009156 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009157 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9158 PointerType::getUnqual(II->getType()),
9159 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009160 return new LoadInst(Ptr);
9161 }
9162 break;
9163 case Intrinsic::ppc_altivec_stvx:
9164 case Intrinsic::ppc_altivec_stvxl:
9165 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009166 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009167 const Type *OpPtrTy =
9168 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009169 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009170 return new StoreInst(II->getOperand(1), Ptr);
9171 }
9172 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009173 case Intrinsic::x86_sse_storeu_ps:
9174 case Intrinsic::x86_sse2_storeu_pd:
9175 case Intrinsic::x86_sse2_storeu_dq:
9176 case Intrinsic::x86_sse2_storel_dq:
9177 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009178 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009179 const Type *OpPtrTy =
9180 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009181 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009182 return new StoreInst(II->getOperand(2), Ptr);
9183 }
9184 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009185
9186 case Intrinsic::x86_sse_cvttss2si: {
9187 // These intrinsics only demands the 0th element of its input vector. If
9188 // we can simplify the input based on that, do so now.
9189 uint64_t UndefElts;
9190 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9191 UndefElts)) {
9192 II->setOperand(1, V);
9193 return II;
9194 }
9195 break;
9196 }
9197
Chris Lattnere2ed0572006-04-06 19:19:17 +00009198 case Intrinsic::ppc_altivec_vperm:
9199 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009200 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009201 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9202
9203 // Check that all of the elements are integer constants or undefs.
9204 bool AllEltsOk = true;
9205 for (unsigned i = 0; i != 16; ++i) {
9206 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9207 !isa<UndefValue>(Mask->getOperand(i))) {
9208 AllEltsOk = false;
9209 break;
9210 }
9211 }
9212
9213 if (AllEltsOk) {
9214 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009215 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9216 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009217 Value *Result = UndefValue::get(Op0->getType());
9218
9219 // Only extract each element once.
9220 Value *ExtractedElts[32];
9221 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9222
9223 for (unsigned i = 0; i != 16; ++i) {
9224 if (isa<UndefValue>(Mask->getOperand(i)))
9225 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009226 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009227 Idx &= 31; // Match the hardware behavior.
9228
9229 if (ExtractedElts[Idx] == 0) {
9230 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009231 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009232 InsertNewInstBefore(Elt, CI);
9233 ExtractedElts[Idx] = Elt;
9234 }
9235
9236 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009237 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9238 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009239 InsertNewInstBefore(cast<Instruction>(Result), CI);
9240 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009241 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009242 }
9243 }
9244 break;
9245
Chris Lattnera728ddc2006-01-13 21:28:09 +00009246 case Intrinsic::stackrestore: {
9247 // If the save is right next to the restore, remove the restore. This can
9248 // happen when variable allocas are DCE'd.
9249 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9250 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9251 BasicBlock::iterator BI = SS;
9252 if (&*++BI == II)
9253 return EraseInstFromFunction(CI);
9254 }
9255 }
9256
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009257 // Scan down this block to see if there is another stack restore in the
9258 // same block without an intervening call/alloca.
9259 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009260 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009261 bool CannotRemove = false;
9262 for (++BI; &*BI != TI; ++BI) {
9263 if (isa<AllocaInst>(BI)) {
9264 CannotRemove = true;
9265 break;
9266 }
9267 if (isa<CallInst>(BI)) {
9268 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009269 CannotRemove = true;
9270 break;
9271 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009272 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009273 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009274 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009275 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009276
9277 // If the stack restore is in a return/unwind block and if there are no
9278 // allocas or calls between the restore and the return, nuke the restore.
9279 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9280 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009281 break;
9282 }
9283 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009284 }
9285
Chris Lattner8b0ea312006-01-13 20:11:04 +00009286 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009287}
9288
9289// InvokeInst simplification
9290//
9291Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009292 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009293}
9294
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009295/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9296/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009297static bool isSafeToEliminateVarargsCast(const CallSite CS,
9298 const CastInst * const CI,
9299 const TargetData * const TD,
9300 const int ix) {
9301 if (!CI->isLosslessCast())
9302 return false;
9303
9304 // The size of ByVal arguments is derived from the type, so we
9305 // can't change to a type with a different size. If the size were
9306 // passed explicitly we could avoid this check.
9307 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9308 return true;
9309
9310 const Type* SrcTy =
9311 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9312 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9313 if (!SrcTy->isSized() || !DstTy->isSized())
9314 return false;
9315 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9316 return false;
9317 return true;
9318}
9319
Chris Lattnera44d8a22003-10-07 22:32:43 +00009320// visitCallSite - Improvements for call and invoke instructions.
9321//
9322Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009323 bool Changed = false;
9324
9325 // If the callee is a constexpr cast of a function, attempt to move the cast
9326 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009327 if (transformConstExprCastCall(CS)) return 0;
9328
Chris Lattner6c266db2003-10-07 22:54:13 +00009329 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009330
Chris Lattner08b22ec2005-05-13 07:09:09 +00009331 if (Function *CalleeF = dyn_cast<Function>(Callee))
9332 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9333 Instruction *OldCall = CS.getInstruction();
9334 // If the call and callee calling conventions don't match, this call must
9335 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009336 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009337 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9338 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009339 if (!OldCall->use_empty())
9340 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9341 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9342 return EraseInstFromFunction(*OldCall);
9343 return 0;
9344 }
9345
Chris Lattner17be6352004-10-18 02:59:09 +00009346 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9347 // This instruction is not reachable, just remove it. We insert a store to
9348 // undef so that we know that this code is not reachable, despite the fact
9349 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009350 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009351 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009352 CS.getInstruction());
9353
9354 if (!CS.getInstruction()->use_empty())
9355 CS.getInstruction()->
9356 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9357
9358 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9359 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009360 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9361 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009362 }
Chris Lattner17be6352004-10-18 02:59:09 +00009363 return EraseInstFromFunction(*CS.getInstruction());
9364 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009365
Duncan Sandscdb6d922007-09-17 10:26:40 +00009366 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9367 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9368 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9369 return transformCallThroughTrampoline(CS);
9370
Chris Lattner6c266db2003-10-07 22:54:13 +00009371 const PointerType *PTy = cast<PointerType>(Callee->getType());
9372 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9373 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009374 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009375 // See if we can optimize any arguments passed through the varargs area of
9376 // the call.
9377 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009378 E = CS.arg_end(); I != E; ++I, ++ix) {
9379 CastInst *CI = dyn_cast<CastInst>(*I);
9380 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9381 *I = CI->getOperand(0);
9382 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009383 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009384 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009385 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009386
Duncan Sandsf0c33542007-12-19 21:13:37 +00009387 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009388 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009389 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009390 Changed = true;
9391 }
9392
Chris Lattner6c266db2003-10-07 22:54:13 +00009393 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009394}
9395
Chris Lattner9fe38862003-06-19 17:00:31 +00009396// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9397// attempt to move the cast to the arguments of the call/invoke.
9398//
9399bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9400 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9401 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009402 if (CE->getOpcode() != Instruction::BitCast ||
9403 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009404 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009405 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009406 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009407 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009408
9409 // Okay, this is a cast from a function to a different type. Unless doing so
9410 // would cause a type conversion of one of our arguments, change this call to
9411 // be a direct call with arguments casted to the appropriate types.
9412 //
9413 const FunctionType *FT = Callee->getFunctionType();
9414 const Type *OldRetTy = Caller->getType();
9415
Devang Patel75e6f022008-03-11 18:04:06 +00009416 if (isa<StructType>(FT->getReturnType()))
9417 return false; // TODO: Handle multiple return values.
9418
Chris Lattnerf78616b2004-01-14 06:06:08 +00009419 // Check to see if we are changing the return type...
9420 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009421 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009422 // Conversion is ok if changing from pointer to int of same size.
9423 !(isa<PointerType>(FT->getReturnType()) &&
9424 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009425 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009426
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009427 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009428 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009429 FT->getReturnType() != Type::VoidTy &&
9430 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009431 return false; // Cannot transform this return value.
9432
Chris Lattner58d74912008-03-12 17:45:29 +00009433 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9434 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009435 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9436 return false; // Attribute not compatible with transformed value.
9437 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009438
Chris Lattnerf78616b2004-01-14 06:06:08 +00009439 // If the callsite is an invoke instruction, and the return value is used by
9440 // a PHI node in a successor, we cannot change the return type of the call
9441 // because there is no place to put the cast instruction (without breaking
9442 // the critical edge). Bail out in this case.
9443 if (!Caller->use_empty())
9444 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9445 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9446 UI != E; ++UI)
9447 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9448 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009449 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009450 return false;
9451 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009452
9453 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9454 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009455
Chris Lattner9fe38862003-06-19 17:00:31 +00009456 CallSite::arg_iterator AI = CS.arg_begin();
9457 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9458 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009459 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009460
9461 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009462 return false; // Cannot transform this parameter value.
9463
Chris Lattner58d74912008-03-12 17:45:29 +00009464 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9465 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009466
Reid Spencer3da59db2006-11-27 01:05:10 +00009467 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009468 // Some conversions are safe even if we do not have a body.
9469 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009470 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009471 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009472 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009473 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9474 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009475 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009476 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009477 }
9478
9479 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009480 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009481 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009482
Chris Lattner58d74912008-03-12 17:45:29 +00009483 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9484 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009485 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009486 // won't be dropping them. Check that these extra arguments have attributes
9487 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009488 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9489 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009490 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009491 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009492 if (PAttrs & ParamAttr::VarArgsIncompatible)
9493 return false;
9494 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009495
Chris Lattner9fe38862003-06-19 17:00:31 +00009496 // Okay, we decided that this is a safe thing to do: go ahead and start
9497 // inserting cast instructions as necessary...
9498 std::vector<Value*> Args;
9499 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009500 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009501 attrVec.reserve(NumCommonArgs);
9502
9503 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009504 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009505
9506 // If the return value is not being used, the type may not be compatible
9507 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009508 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009509
9510 // Add the new return attributes.
9511 if (RAttrs)
9512 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009513
9514 AI = CS.arg_begin();
9515 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9516 const Type *ParamTy = FT->getParamType(i);
9517 if ((*AI)->getType() == ParamTy) {
9518 Args.push_back(*AI);
9519 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009520 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009521 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009522 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009523 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009524 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009525
9526 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009527 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009528 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009529 }
9530
9531 // If the function takes more arguments than the call was taking, add them
9532 // now...
9533 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9534 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9535
9536 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009537 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009538 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009539 cerr << "WARNING: While resolving call to function '"
9540 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009541 } else {
9542 // Add all of the arguments in their promoted form to the arg list...
9543 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9544 const Type *PTy = getPromotedType((*AI)->getType());
9545 if (PTy != (*AI)->getType()) {
9546 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009547 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9548 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009549 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009550 InsertNewInstBefore(Cast, *Caller);
9551 Args.push_back(Cast);
9552 } else {
9553 Args.push_back(*AI);
9554 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009555
Duncan Sandse1e520f2008-01-13 08:02:44 +00009556 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009557 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009558 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9559 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009560 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009561 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009562
9563 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009564 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009565
Chris Lattner58d74912008-03-12 17:45:29 +00009566 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009567
Chris Lattner9fe38862003-06-19 17:00:31 +00009568 Instruction *NC;
9569 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009570 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009571 Args.begin(), Args.end(),
9572 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009573 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009574 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009575 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009576 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9577 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009578 CallInst *CI = cast<CallInst>(Caller);
9579 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009580 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009581 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009582 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009583 }
9584
Chris Lattner6934a042007-02-11 01:23:03 +00009585 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009586 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009587 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009588 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009589 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009590 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009591 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009592
9593 // If this is an invoke instruction, we should insert it after the first
9594 // non-phi, instruction in the normal successor block.
9595 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9596 BasicBlock::iterator I = II->getNormalDest()->begin();
9597 while (isa<PHINode>(I)) ++I;
9598 InsertNewInstBefore(NC, *I);
9599 } else {
9600 // Otherwise, it's a call, just insert cast right after the call instr
9601 InsertNewInstBefore(NC, *Caller);
9602 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009603 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009604 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009605 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009606 }
9607 }
9608
9609 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9610 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009611 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009612 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009613 return true;
9614}
9615
Duncan Sandscdb6d922007-09-17 10:26:40 +00009616// transformCallThroughTrampoline - Turn a call to a function created by the
9617// init_trampoline intrinsic into a direct call to the underlying function.
9618//
9619Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9620 Value *Callee = CS.getCalledValue();
9621 const PointerType *PTy = cast<PointerType>(Callee->getType());
9622 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009623 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009624
9625 // If the call already has the 'nest' attribute somewhere then give up -
9626 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009627 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009628 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009629
9630 IntrinsicInst *Tramp =
9631 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9632
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009633 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009634 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9635 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9636
Chris Lattner58d74912008-03-12 17:45:29 +00009637 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9638 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009639 unsigned NestIdx = 1;
9640 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009641 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009642
9643 // Look for a parameter marked with the 'nest' attribute.
9644 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9645 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009646 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009647 // Record the parameter type and any other attributes.
9648 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009649 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009650 break;
9651 }
9652
9653 if (NestTy) {
9654 Instruction *Caller = CS.getInstruction();
9655 std::vector<Value*> NewArgs;
9656 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9657
Chris Lattner58d74912008-03-12 17:45:29 +00009658 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9659 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009660
Duncan Sandscdb6d922007-09-17 10:26:40 +00009661 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009662 // mean appending it. Likewise for attributes.
9663
9664 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009665 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9666 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009667
Duncan Sandscdb6d922007-09-17 10:26:40 +00009668 {
9669 unsigned Idx = 1;
9670 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9671 do {
9672 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009673 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009674 Value *NestVal = Tramp->getOperand(3);
9675 if (NestVal->getType() != NestTy)
9676 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9677 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009678 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009679 }
9680
9681 if (I == E)
9682 break;
9683
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009684 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009685 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009686 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009687 NewAttrs.push_back
9688 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009689
9690 ++Idx, ++I;
9691 } while (1);
9692 }
9693
9694 // The trampoline may have been bitcast to a bogus type (FTy).
9695 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009696 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009697
Duncan Sandscdb6d922007-09-17 10:26:40 +00009698 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009699 NewTypes.reserve(FTy->getNumParams()+1);
9700
Duncan Sandscdb6d922007-09-17 10:26:40 +00009701 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009702 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009703 {
9704 unsigned Idx = 1;
9705 FunctionType::param_iterator I = FTy->param_begin(),
9706 E = FTy->param_end();
9707
9708 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009709 if (Idx == NestIdx)
9710 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009711 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009712
9713 if (I == E)
9714 break;
9715
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009716 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009717 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009718
9719 ++Idx, ++I;
9720 } while (1);
9721 }
9722
9723 // Replace the trampoline call with a direct call. Let the generic
9724 // code sort out any function type mismatches.
9725 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009726 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009727 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9728 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009729 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009730
9731 Instruction *NewCaller;
9732 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009733 NewCaller = InvokeInst::Create(NewCallee,
9734 II->getNormalDest(), II->getUnwindDest(),
9735 NewArgs.begin(), NewArgs.end(),
9736 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009737 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009738 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009739 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009740 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9741 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009742 if (cast<CallInst>(Caller)->isTailCall())
9743 cast<CallInst>(NewCaller)->setTailCall();
9744 cast<CallInst>(NewCaller)->
9745 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009746 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009747 }
9748 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9749 Caller->replaceAllUsesWith(NewCaller);
9750 Caller->eraseFromParent();
9751 RemoveFromWorkList(Caller);
9752 return 0;
9753 }
9754 }
9755
9756 // Replace the trampoline call with a direct call. Since there is no 'nest'
9757 // parameter, there is no need to adjust the argument list. Let the generic
9758 // code sort out any function type mismatches.
9759 Constant *NewCallee =
9760 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9761 CS.setCalledFunction(NewCallee);
9762 return CS.getInstruction();
9763}
9764
Chris Lattner7da52b22006-11-01 04:51:18 +00009765/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9766/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9767/// and a single binop.
9768Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9769 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009770 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9771 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009772 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009773 Value *LHSVal = FirstInst->getOperand(0);
9774 Value *RHSVal = FirstInst->getOperand(1);
9775
9776 const Type *LHSType = LHSVal->getType();
9777 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009778
9779 // Scan to see if all operands are the same opcode, all have one use, and all
9780 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009781 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009782 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009783 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009784 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009785 // types or GEP's with different index types.
9786 I->getOperand(0)->getType() != LHSType ||
9787 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009788 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009789
9790 // If they are CmpInst instructions, check their predicates
9791 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9792 if (cast<CmpInst>(I)->getPredicate() !=
9793 cast<CmpInst>(FirstInst)->getPredicate())
9794 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009795
9796 // Keep track of which operand needs a phi node.
9797 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9798 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009799 }
9800
Chris Lattner53738a42006-11-08 19:42:28 +00009801 // Otherwise, this is safe to transform, determine if it is profitable.
9802
9803 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9804 // Indexes are often folded into load/store instructions, so we don't want to
9805 // hide them behind a phi.
9806 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9807 return 0;
9808
Chris Lattner7da52b22006-11-01 04:51:18 +00009809 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009810 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009811 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009812 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009813 NewLHS = PHINode::Create(LHSType,
9814 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009815 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9816 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009817 InsertNewInstBefore(NewLHS, PN);
9818 LHSVal = NewLHS;
9819 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009820
9821 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009822 NewRHS = PHINode::Create(RHSType,
9823 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009824 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9825 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009826 InsertNewInstBefore(NewRHS, PN);
9827 RHSVal = NewRHS;
9828 }
9829
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009830 // Add all operands to the new PHIs.
9831 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9832 if (NewLHS) {
9833 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9834 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9835 }
9836 if (NewRHS) {
9837 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9838 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9839 }
9840 }
9841
Chris Lattner7da52b22006-11-01 04:51:18 +00009842 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009843 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009844 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009845 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009846 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009847 else {
9848 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009849 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009850 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009851}
9852
Chris Lattner76c73142006-11-01 07:13:54 +00009853/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9854/// of the block that defines it. This means that it must be obvious the value
9855/// of the load is not changed from the point of the load to the end of the
9856/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009857///
9858/// Finally, it is safe, but not profitable, to sink a load targetting a
9859/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9860/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009861static bool isSafeToSinkLoad(LoadInst *L) {
9862 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9863
9864 for (++BBI; BBI != E; ++BBI)
9865 if (BBI->mayWriteToMemory())
9866 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009867
9868 // Check for non-address taken alloca. If not address-taken already, it isn't
9869 // profitable to do this xform.
9870 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9871 bool isAddressTaken = false;
9872 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9873 UI != E; ++UI) {
9874 if (isa<LoadInst>(UI)) continue;
9875 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9876 // If storing TO the alloca, then the address isn't taken.
9877 if (SI->getOperand(1) == AI) continue;
9878 }
9879 isAddressTaken = true;
9880 break;
9881 }
9882
9883 if (!isAddressTaken)
9884 return false;
9885 }
9886
Chris Lattner76c73142006-11-01 07:13:54 +00009887 return true;
9888}
9889
Chris Lattner9fe38862003-06-19 17:00:31 +00009890
Chris Lattnerbac32862004-11-14 19:13:23 +00009891// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9892// operator and they all are only used by the PHI, PHI together their
9893// inputs, and do the operation once, to the result of the PHI.
9894Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9895 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9896
9897 // Scan the instruction, looking for input operations that can be folded away.
9898 // If all input operands to the phi are the same instruction (e.g. a cast from
9899 // the same type or "+42") we can pull the operation through the PHI, reducing
9900 // code size and simplifying code.
9901 Constant *ConstantOp = 0;
9902 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009903 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009904 if (isa<CastInst>(FirstInst)) {
9905 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009906 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009907 // Can fold binop, compare or shift here if the RHS is a constant,
9908 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009909 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009910 if (ConstantOp == 0)
9911 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009912 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9913 isVolatile = LI->isVolatile();
9914 // We can't sink the load if the loaded value could be modified between the
9915 // load and the PHI.
9916 if (LI->getParent() != PN.getIncomingBlock(0) ||
9917 !isSafeToSinkLoad(LI))
9918 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009919 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009920 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009921 return FoldPHIArgBinOpIntoPHI(PN);
9922 // Can't handle general GEPs yet.
9923 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009924 } else {
9925 return 0; // Cannot fold this operation.
9926 }
9927
9928 // Check to see if all arguments are the same operation.
9929 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9930 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9931 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009932 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009933 return 0;
9934 if (CastSrcTy) {
9935 if (I->getOperand(0)->getType() != CastSrcTy)
9936 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009937 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009938 // We can't sink the load if the loaded value could be modified between
9939 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009940 if (LI->isVolatile() != isVolatile ||
9941 LI->getParent() != PN.getIncomingBlock(i) ||
9942 !isSafeToSinkLoad(LI))
9943 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009944
9945 // If the PHI is volatile and its block has multiple successors, sinking
9946 // it would remove a load of the volatile value from the path through the
9947 // other successor.
9948 if (isVolatile &&
9949 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9950 return 0;
9951
9952
Chris Lattnerbac32862004-11-14 19:13:23 +00009953 } else if (I->getOperand(1) != ConstantOp) {
9954 return 0;
9955 }
9956 }
9957
9958 // Okay, they are all the same operation. Create a new PHI node of the
9959 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009960 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9961 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009962 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009963
9964 Value *InVal = FirstInst->getOperand(0);
9965 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009966
9967 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009968 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9969 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9970 if (NewInVal != InVal)
9971 InVal = 0;
9972 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9973 }
9974
9975 Value *PhiVal;
9976 if (InVal) {
9977 // The new PHI unions all of the same values together. This is really
9978 // common, so we handle it intelligently here for compile-time speed.
9979 PhiVal = InVal;
9980 delete NewPN;
9981 } else {
9982 InsertNewInstBefore(NewPN, PN);
9983 PhiVal = NewPN;
9984 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009985
Chris Lattnerbac32862004-11-14 19:13:23 +00009986 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009987 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009988 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009989 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009990 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009991 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009992 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009993 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009994 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9995
9996 // If this was a volatile load that we are merging, make sure to loop through
9997 // and mark all the input loads as non-volatile. If we don't do this, we will
9998 // insert a new volatile load and the old ones will not be deletable.
9999 if (isVolatile)
10000 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10001 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10002
10003 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010004}
Chris Lattnera1be5662002-05-02 17:06:02 +000010005
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010006/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10007/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010008static bool DeadPHICycle(PHINode *PN,
10009 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010010 if (PN->use_empty()) return true;
10011 if (!PN->hasOneUse()) return false;
10012
10013 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010014 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010015 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010016
10017 // Don't scan crazily complex things.
10018 if (PotentiallyDeadPHIs.size() == 16)
10019 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010020
10021 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10022 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010023
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010024 return false;
10025}
10026
Chris Lattnercf5008a2007-11-06 21:52:06 +000010027/// PHIsEqualValue - Return true if this phi node is always equal to
10028/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10029/// z = some value; x = phi (y, z); y = phi (x, z)
10030static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10031 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10032 // See if we already saw this PHI node.
10033 if (!ValueEqualPHIs.insert(PN))
10034 return true;
10035
10036 // Don't scan crazily complex things.
10037 if (ValueEqualPHIs.size() == 16)
10038 return false;
10039
10040 // Scan the operands to see if they are either phi nodes or are equal to
10041 // the value.
10042 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10043 Value *Op = PN->getIncomingValue(i);
10044 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10045 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10046 return false;
10047 } else if (Op != NonPhiInVal)
10048 return false;
10049 }
10050
10051 return true;
10052}
10053
10054
Chris Lattner473945d2002-05-06 18:06:38 +000010055// PHINode simplification
10056//
Chris Lattner7e708292002-06-25 16:13:24 +000010057Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010058 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010059 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010060
Owen Anderson7e057142006-07-10 22:03:18 +000010061 if (Value *V = PN.hasConstantValue())
10062 return ReplaceInstUsesWith(PN, V);
10063
Owen Anderson7e057142006-07-10 22:03:18 +000010064 // If all PHI operands are the same operation, pull them through the PHI,
10065 // reducing code size.
10066 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10067 PN.getIncomingValue(0)->hasOneUse())
10068 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10069 return Result;
10070
10071 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10072 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10073 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010074 if (PN.hasOneUse()) {
10075 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10076 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010077 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010078 PotentiallyDeadPHIs.insert(&PN);
10079 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10080 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10081 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010082
10083 // If this phi has a single use, and if that use just computes a value for
10084 // the next iteration of a loop, delete the phi. This occurs with unused
10085 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10086 // common case here is good because the only other things that catch this
10087 // are induction variable analysis (sometimes) and ADCE, which is only run
10088 // late.
10089 if (PHIUser->hasOneUse() &&
10090 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10091 PHIUser->use_back() == &PN) {
10092 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10093 }
10094 }
Owen Anderson7e057142006-07-10 22:03:18 +000010095
Chris Lattnercf5008a2007-11-06 21:52:06 +000010096 // We sometimes end up with phi cycles that non-obviously end up being the
10097 // same value, for example:
10098 // z = some value; x = phi (y, z); y = phi (x, z)
10099 // where the phi nodes don't necessarily need to be in the same block. Do a
10100 // quick check to see if the PHI node only contains a single non-phi value, if
10101 // so, scan to see if the phi cycle is actually equal to that value.
10102 {
10103 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10104 // Scan for the first non-phi operand.
10105 while (InValNo != NumOperandVals &&
10106 isa<PHINode>(PN.getIncomingValue(InValNo)))
10107 ++InValNo;
10108
10109 if (InValNo != NumOperandVals) {
10110 Value *NonPhiInVal = PN.getOperand(InValNo);
10111
10112 // Scan the rest of the operands to see if there are any conflicts, if so
10113 // there is no need to recursively scan other phis.
10114 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10115 Value *OpVal = PN.getIncomingValue(InValNo);
10116 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10117 break;
10118 }
10119
10120 // If we scanned over all operands, then we have one unique value plus
10121 // phi values. Scan PHI nodes to see if they all merge in each other or
10122 // the value.
10123 if (InValNo == NumOperandVals) {
10124 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10125 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10126 return ReplaceInstUsesWith(PN, NonPhiInVal);
10127 }
10128 }
10129 }
Chris Lattner60921c92003-12-19 05:58:40 +000010130 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010131}
10132
Reid Spencer17212df2006-12-12 09:18:51 +000010133static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10134 Instruction *InsertPoint,
10135 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010136 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10137 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010138 // We must cast correctly to the pointer type. Ensure that we
10139 // sign extend the integer value if it is smaller as this is
10140 // used for address computation.
10141 Instruction::CastOps opcode =
10142 (VTySize < PtrSize ? Instruction::SExt :
10143 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10144 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010145}
10146
Chris Lattnera1be5662002-05-02 17:06:02 +000010147
Chris Lattner7e708292002-06-25 16:13:24 +000010148Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010149 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010150 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010151 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010152 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010153 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010154
Chris Lattnere87597f2004-10-16 18:11:37 +000010155 if (isa<UndefValue>(GEP.getOperand(0)))
10156 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10157
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010158 bool HasZeroPointerIndex = false;
10159 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10160 HasZeroPointerIndex = C->isNullValue();
10161
10162 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010163 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010164
Chris Lattner28977af2004-04-05 01:30:19 +000010165 // Eliminate unneeded casts for indices.
10166 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010167
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010168 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010169 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010170 if (isa<SequentialType>(*GTI)) {
10171 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010172 if (CI->getOpcode() == Instruction::ZExt ||
10173 CI->getOpcode() == Instruction::SExt) {
10174 const Type *SrcTy = CI->getOperand(0)->getType();
10175 // We can eliminate a cast from i32 to i64 iff the target
10176 // is a 32-bit pointer target.
10177 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10178 MadeChange = true;
10179 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010180 }
10181 }
10182 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010183 // If we are using a wider index than needed for this platform, shrink it
10184 // to what we need. If the incoming value needs a cast instruction,
10185 // insert it. This explicit cast can make subsequent optimizations more
10186 // obvious.
10187 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010188 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010189 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010190 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010191 MadeChange = true;
10192 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010193 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10194 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010195 GEP.setOperand(i, Op);
10196 MadeChange = true;
10197 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010198 }
Chris Lattner28977af2004-04-05 01:30:19 +000010199 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010200 }
Chris Lattner28977af2004-04-05 01:30:19 +000010201 if (MadeChange) return &GEP;
10202
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010203 // If this GEP instruction doesn't move the pointer, and if the input operand
10204 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10205 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010206 if (GEP.hasAllZeroIndices()) {
10207 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10208 // If the bitcast is of an allocation, and the allocation will be
10209 // converted to match the type of the cast, don't touch this.
10210 if (isa<AllocationInst>(BCI->getOperand(0))) {
10211 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010212 if (Instruction *I = visitBitCast(*BCI)) {
10213 if (I != BCI) {
10214 I->takeName(BCI);
10215 BCI->getParent()->getInstList().insert(BCI, I);
10216 ReplaceInstUsesWith(*BCI, I);
10217 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010218 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010219 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010220 }
10221 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10222 }
10223 }
10224
Chris Lattner90ac28c2002-08-02 19:29:35 +000010225 // Combine Indices - If the source pointer to this getelementptr instruction
10226 // is a getelementptr instruction, combine the indices of the two
10227 // getelementptr instructions into a single instruction.
10228 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010229 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010230 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010231 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010232
10233 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010234 // Note that if our source is a gep chain itself that we wait for that
10235 // chain to be resolved before we perform this transformation. This
10236 // avoids us creating a TON of code in some cases.
10237 //
10238 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10239 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10240 return 0; // Wait until our source is folded to completion.
10241
Chris Lattner72588fc2007-02-15 22:48:32 +000010242 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010243
10244 // Find out whether the last index in the source GEP is a sequential idx.
10245 bool EndsWithSequential = false;
10246 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10247 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010248 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010249
Chris Lattner90ac28c2002-08-02 19:29:35 +000010250 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010251 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010252 // Replace: gep (gep %P, long B), long A, ...
10253 // With: T = long A+B; gep %P, T, ...
10254 //
Chris Lattner620ce142004-05-07 22:09:22 +000010255 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010256 if (SO1 == Constant::getNullValue(SO1->getType())) {
10257 Sum = GO1;
10258 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10259 Sum = SO1;
10260 } else {
10261 // If they aren't the same type, convert both to an integer of the
10262 // target's pointer size.
10263 if (SO1->getType() != GO1->getType()) {
10264 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010265 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010266 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010267 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010268 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010269 unsigned PS = TD->getPointerSizeInBits();
10270 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010271 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010272 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010273
Duncan Sands514ab342007-11-01 20:53:16 +000010274 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010275 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010276 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010277 } else {
10278 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010279 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10280 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010281 }
10282 }
10283 }
Chris Lattner620ce142004-05-07 22:09:22 +000010284 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10285 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10286 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010287 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010288 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010289 }
Chris Lattner28977af2004-04-05 01:30:19 +000010290 }
Chris Lattner620ce142004-05-07 22:09:22 +000010291
10292 // Recycle the GEP we already have if possible.
10293 if (SrcGEPOperands.size() == 2) {
10294 GEP.setOperand(0, SrcGEPOperands[0]);
10295 GEP.setOperand(1, Sum);
10296 return &GEP;
10297 } else {
10298 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10299 SrcGEPOperands.end()-1);
10300 Indices.push_back(Sum);
10301 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10302 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010303 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010304 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010305 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010306 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010307 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10308 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010309 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10310 }
10311
10312 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010313 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10314 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010315
Chris Lattner620ce142004-05-07 22:09:22 +000010316 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010317 // GEP of global variable. If all of the indices for this GEP are
10318 // constants, we can promote this to a constexpr instead of an instruction.
10319
10320 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010321 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010322 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10323 for (; I != E && isa<Constant>(*I); ++I)
10324 Indices.push_back(cast<Constant>(*I));
10325
10326 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010327 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10328 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010329
10330 // Replace all uses of the GEP with the new constexpr...
10331 return ReplaceInstUsesWith(GEP, CE);
10332 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010333 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010334 if (!isa<PointerType>(X->getType())) {
10335 // Not interesting. Source pointer must be a cast from pointer.
10336 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010337 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10338 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010339 //
10340 // This occurs when the program declares an array extern like "int X[];"
10341 //
10342 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10343 const PointerType *XTy = cast<PointerType>(X->getType());
10344 if (const ArrayType *XATy =
10345 dyn_cast<ArrayType>(XTy->getElementType()))
10346 if (const ArrayType *CATy =
10347 dyn_cast<ArrayType>(CPTy->getElementType()))
10348 if (CATy->getElementType() == XATy->getElementType()) {
10349 // At this point, we know that the cast source type is a pointer
10350 // to an array of the same type as the destination pointer
10351 // array. Because the array type is never stepped over (there
10352 // is a leading zero) we can fold the cast into this GEP.
10353 GEP.setOperand(0, X);
10354 return &GEP;
10355 }
10356 } else if (GEP.getNumOperands() == 2) {
10357 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010358 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10359 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010360 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10361 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10362 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010363 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10364 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010365 Value *Idx[2];
10366 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10367 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010368 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010369 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010370 // V and GEP are both pointer types --> BitCast
10371 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010372 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010373
10374 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010375 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010376 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010377 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010378
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010379 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010380 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010381 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010382
10383 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10384 // allow either a mul, shift, or constant here.
10385 Value *NewIdx = 0;
10386 ConstantInt *Scale = 0;
10387 if (ArrayEltSize == 1) {
10388 NewIdx = GEP.getOperand(1);
10389 Scale = ConstantInt::get(NewIdx->getType(), 1);
10390 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010391 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010392 Scale = CI;
10393 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10394 if (Inst->getOpcode() == Instruction::Shl &&
10395 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010396 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10397 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10398 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010399 NewIdx = Inst->getOperand(0);
10400 } else if (Inst->getOpcode() == Instruction::Mul &&
10401 isa<ConstantInt>(Inst->getOperand(1))) {
10402 Scale = cast<ConstantInt>(Inst->getOperand(1));
10403 NewIdx = Inst->getOperand(0);
10404 }
10405 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010406
Chris Lattner7835cdd2005-09-13 18:36:04 +000010407 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010408 // out, perform the transformation. Note, we don't know whether Scale is
10409 // signed or not. We'll use unsigned version of division/modulo
10410 // operation after making sure Scale doesn't have the sign bit set.
10411 if (Scale && Scale->getSExtValue() >= 0LL &&
10412 Scale->getZExtValue() % ArrayEltSize == 0) {
10413 Scale = ConstantInt::get(Scale->getType(),
10414 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010415 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010416 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010417 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010418 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010419 NewIdx = InsertNewInstBefore(Sc, GEP);
10420 }
10421
10422 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010423 Value *Idx[2];
10424 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10425 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010426 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010427 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010428 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10429 // The NewGEP must be pointer typed, so must the old one -> BitCast
10430 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010431 }
10432 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010433 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010434 }
10435
Chris Lattner8a2a3112001-12-14 16:52:21 +000010436 return 0;
10437}
10438
Chris Lattner0864acf2002-11-04 16:18:53 +000010439Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10440 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010441 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010442 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10443 const Type *NewTy =
10444 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010445 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010446
10447 // Create and insert the replacement instruction...
10448 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010449 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010450 else {
10451 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010452 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010453 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010454
10455 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010456
Chris Lattner0864acf2002-11-04 16:18:53 +000010457 // Scan to the end of the allocation instructions, to skip over a block of
10458 // allocas if possible...
10459 //
10460 BasicBlock::iterator It = New;
10461 while (isa<AllocationInst>(*It)) ++It;
10462
10463 // Now that I is pointing to the first non-allocation-inst in the block,
10464 // insert our getelementptr instruction...
10465 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010466 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010467 Value *Idx[2];
10468 Idx[0] = NullIdx;
10469 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010470 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10471 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010472
10473 // Now make everything use the getelementptr instead of the original
10474 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010475 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010476 } else if (isa<UndefValue>(AI.getArraySize())) {
10477 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010478 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010479 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010480
10481 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10482 // Note that we only do this for alloca's, because malloc should allocate and
10483 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010484 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010485 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010486 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10487
Chris Lattner0864acf2002-11-04 16:18:53 +000010488 return 0;
10489}
10490
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010491Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10492 Value *Op = FI.getOperand(0);
10493
Chris Lattner17be6352004-10-18 02:59:09 +000010494 // free undef -> unreachable.
10495 if (isa<UndefValue>(Op)) {
10496 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010497 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010498 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010499 return EraseInstFromFunction(FI);
10500 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010501
Chris Lattner6160e852004-02-28 04:57:37 +000010502 // If we have 'free null' delete the instruction. This can happen in stl code
10503 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010504 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010505 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010506
10507 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10508 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10509 FI.setOperand(0, CI->getOperand(0));
10510 return &FI;
10511 }
10512
10513 // Change free (gep X, 0,0,0,0) into free(X)
10514 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10515 if (GEPI->hasAllZeroIndices()) {
10516 AddToWorkList(GEPI);
10517 FI.setOperand(0, GEPI->getOperand(0));
10518 return &FI;
10519 }
10520 }
10521
10522 // Change free(malloc) into nothing, if the malloc has a single use.
10523 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10524 if (MI->hasOneUse()) {
10525 EraseInstFromFunction(FI);
10526 return EraseInstFromFunction(*MI);
10527 }
Chris Lattner6160e852004-02-28 04:57:37 +000010528
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010529 return 0;
10530}
10531
10532
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010533/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010534static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010535 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010536 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010537 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010538
Devang Patel99db6ad2007-10-18 19:52:32 +000010539 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10540 // Instead of loading constant c string, use corresponding integer value
10541 // directly if string length is small enough.
10542 const std::string &Str = CE->getOperand(0)->getStringValue();
10543 if (!Str.empty()) {
10544 unsigned len = Str.length();
10545 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10546 unsigned numBits = Ty->getPrimitiveSizeInBits();
10547 // Replace LI with immediate integer store.
10548 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010549 APInt StrVal(numBits, 0);
10550 APInt SingleChar(numBits, 0);
10551 if (TD->isLittleEndian()) {
10552 for (signed i = len-1; i >= 0; i--) {
10553 SingleChar = (uint64_t) Str[i];
10554 StrVal = (StrVal << 8) | SingleChar;
10555 }
10556 } else {
10557 for (unsigned i = 0; i < len; i++) {
10558 SingleChar = (uint64_t) Str[i];
10559 StrVal = (StrVal << 8) | SingleChar;
10560 }
10561 // Append NULL at the end.
10562 SingleChar = 0;
10563 StrVal = (StrVal << 8) | SingleChar;
10564 }
10565 Value *NL = ConstantInt::get(StrVal);
10566 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010567 }
10568 }
10569 }
10570
Chris Lattnerb89e0712004-07-13 01:49:43 +000010571 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010572 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010573 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010574
Reid Spencer42230162007-01-22 05:51:25 +000010575 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010576 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010577 // If the source is an array, the code below will not succeed. Check to
10578 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10579 // constants.
10580 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10581 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10582 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010583 Value *Idxs[2];
10584 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10585 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010586 SrcTy = cast<PointerType>(CastOp->getType());
10587 SrcPTy = SrcTy->getElementType();
10588 }
10589
Reid Spencer42230162007-01-22 05:51:25 +000010590 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010591 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010592 // Do not allow turning this into a load of an integer, which is then
10593 // casted to a pointer, this pessimizes pointer analysis a lot.
10594 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010595 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10596 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010597
Chris Lattnerf9527852005-01-31 04:50:46 +000010598 // Okay, we are casting from one integer or pointer type to another of
10599 // the same size. Instead of casting the pointer before the load, cast
10600 // the result of the loaded value.
10601 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10602 CI->getName(),
10603 LI.isVolatile()),LI);
10604 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010605 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010606 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010607 }
10608 }
10609 return 0;
10610}
10611
Chris Lattnerc10aced2004-09-19 18:43:46 +000010612/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010613/// from this value cannot trap. If it is not obviously safe to load from the
10614/// specified pointer, we do a quick local scan of the basic block containing
10615/// ScanFrom, to determine if the address is already accessed.
10616static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010617 // If it is an alloca it is always safe to load from.
10618 if (isa<AllocaInst>(V)) return true;
10619
Duncan Sands46318cd2007-09-19 10:25:38 +000010620 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010621 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010622 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010623 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010624
10625 // Otherwise, be a little bit agressive by scanning the local block where we
10626 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010627 // from/to. If so, the previous load or store would have already trapped,
10628 // so there is no harm doing an extra load (also, CSE will later eliminate
10629 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010630 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10631
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010632 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010633 --BBI;
10634
10635 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10636 if (LI->getOperand(0) == V) return true;
10637 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10638 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010639
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010640 }
Chris Lattner8a375202004-09-19 19:18:10 +000010641 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010642}
10643
Chris Lattner8d2e8882007-08-11 18:48:48 +000010644/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10645/// until we find the underlying object a pointer is referring to or something
10646/// we don't understand. Note that the returned pointer may be offset from the
10647/// input, because we ignore GEP indices.
10648static Value *GetUnderlyingObject(Value *Ptr) {
10649 while (1) {
10650 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10651 if (CE->getOpcode() == Instruction::BitCast ||
10652 CE->getOpcode() == Instruction::GetElementPtr)
10653 Ptr = CE->getOperand(0);
10654 else
10655 return Ptr;
10656 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10657 Ptr = BCI->getOperand(0);
10658 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10659 Ptr = GEP->getOperand(0);
10660 } else {
10661 return Ptr;
10662 }
10663 }
10664}
10665
Chris Lattner833b8a42003-06-26 05:06:25 +000010666Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10667 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010668
Dan Gohman9941f742007-07-20 16:34:21 +000010669 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010670 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10671 if (KnownAlign >
10672 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10673 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010674 LI.setAlignment(KnownAlign);
10675
Chris Lattner37366c12005-05-01 04:24:53 +000010676 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010677 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010678 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010679 return Res;
10680
10681 // None of the following transforms are legal for volatile loads.
10682 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010683
Chris Lattner62f254d2005-09-12 22:00:15 +000010684 if (&LI.getParent()->front() != &LI) {
10685 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010686 // If the instruction immediately before this is a store to the same
10687 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010688 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10689 if (SI->getOperand(1) == LI.getOperand(0))
10690 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010691 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10692 if (LIB->getOperand(0) == LI.getOperand(0))
10693 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010694 }
Chris Lattner37366c12005-05-01 04:24:53 +000010695
Christopher Lambb15147e2007-12-29 07:56:53 +000010696 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10697 const Value *GEPI0 = GEPI->getOperand(0);
10698 // TODO: Consider a target hook for valid address spaces for this xform.
10699 if (isa<ConstantPointerNull>(GEPI0) &&
10700 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010701 // Insert a new store to null instruction before the load to indicate
10702 // that this code is not reachable. We do this instead of inserting
10703 // an unreachable instruction directly because we cannot modify the
10704 // CFG.
10705 new StoreInst(UndefValue::get(LI.getType()),
10706 Constant::getNullValue(Op->getType()), &LI);
10707 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10708 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010709 }
Chris Lattner37366c12005-05-01 04:24:53 +000010710
Chris Lattnere87597f2004-10-16 18:11:37 +000010711 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010712 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010713 // TODO: Consider a target hook for valid address spaces for this xform.
10714 if (isa<UndefValue>(C) || (C->isNullValue() &&
10715 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010716 // Insert a new store to null instruction before the load to indicate that
10717 // this code is not reachable. We do this instead of inserting an
10718 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010719 new StoreInst(UndefValue::get(LI.getType()),
10720 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010721 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010722 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010723
Chris Lattnere87597f2004-10-16 18:11:37 +000010724 // Instcombine load (constant global) into the value loaded.
10725 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010726 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010727 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010728
Chris Lattnere87597f2004-10-16 18:11:37 +000010729 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010730 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010731 if (CE->getOpcode() == Instruction::GetElementPtr) {
10732 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010733 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010734 if (Constant *V =
10735 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010736 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010737 if (CE->getOperand(0)->isNullValue()) {
10738 // Insert a new store to null instruction before the load to indicate
10739 // that this code is not reachable. We do this instead of inserting
10740 // an unreachable instruction directly because we cannot modify the
10741 // CFG.
10742 new StoreInst(UndefValue::get(LI.getType()),
10743 Constant::getNullValue(Op->getType()), &LI);
10744 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10745 }
10746
Reid Spencer3da59db2006-11-27 01:05:10 +000010747 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010748 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010749 return Res;
10750 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010751 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010752 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010753
10754 // If this load comes from anywhere in a constant global, and if the global
10755 // is all undef or zero, we know what it loads.
10756 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10757 if (GV->isConstant() && GV->hasInitializer()) {
10758 if (GV->getInitializer()->isNullValue())
10759 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10760 else if (isa<UndefValue>(GV->getInitializer()))
10761 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10762 }
10763 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010764
Chris Lattner37366c12005-05-01 04:24:53 +000010765 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010766 // Change select and PHI nodes to select values instead of addresses: this
10767 // helps alias analysis out a lot, allows many others simplifications, and
10768 // exposes redundancy in the code.
10769 //
10770 // Note that we cannot do the transformation unless we know that the
10771 // introduced loads cannot trap! Something like this is valid as long as
10772 // the condition is always false: load (select bool %C, int* null, int* %G),
10773 // but it would not be valid if we transformed it to load from null
10774 // unconditionally.
10775 //
10776 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10777 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010778 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10779 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010780 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010781 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010782 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010783 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010784 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010785 }
10786
Chris Lattner684fe212004-09-23 15:46:00 +000010787 // load (select (cond, null, P)) -> load P
10788 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10789 if (C->isNullValue()) {
10790 LI.setOperand(0, SI->getOperand(2));
10791 return &LI;
10792 }
10793
10794 // load (select (cond, P, null)) -> load P
10795 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10796 if (C->isNullValue()) {
10797 LI.setOperand(0, SI->getOperand(1));
10798 return &LI;
10799 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010800 }
10801 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010802 return 0;
10803}
10804
Reid Spencer55af2b52007-01-19 21:20:31 +000010805/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010806/// when possible.
10807static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10808 User *CI = cast<User>(SI.getOperand(1));
10809 Value *CastOp = CI->getOperand(0);
10810
10811 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10812 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10813 const Type *SrcPTy = SrcTy->getElementType();
10814
Reid Spencer42230162007-01-22 05:51:25 +000010815 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010816 // If the source is an array, the code below will not succeed. Check to
10817 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10818 // constants.
10819 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10820 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10821 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010822 Value* Idxs[2];
10823 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10824 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010825 SrcTy = cast<PointerType>(CastOp->getType());
10826 SrcPTy = SrcTy->getElementType();
10827 }
10828
Reid Spencer67f827c2007-01-20 23:35:48 +000010829 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10830 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10831 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010832
10833 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010834 // the same size. Instead of casting the pointer before
10835 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010836 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010837 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010838 Instruction::CastOps opcode = Instruction::BitCast;
10839 const Type* CastSrcTy = SIOp0->getType();
10840 const Type* CastDstTy = SrcPTy;
10841 if (isa<PointerType>(CastDstTy)) {
10842 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010843 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010844 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010845 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010846 opcode = Instruction::PtrToInt;
10847 }
10848 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010849 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010850 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010851 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010852 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010853 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010854 return new StoreInst(NewCast, CastOp);
10855 }
10856 }
10857 }
10858 return 0;
10859}
10860
Chris Lattner2f503e62005-01-31 05:36:43 +000010861Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10862 Value *Val = SI.getOperand(0);
10863 Value *Ptr = SI.getOperand(1);
10864
10865 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010866 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010867 ++NumCombined;
10868 return 0;
10869 }
Chris Lattner836692d2007-01-15 06:51:56 +000010870
10871 // If the RHS is an alloca with a single use, zapify the store, making the
10872 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010873 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010874 if (isa<AllocaInst>(Ptr)) {
10875 EraseInstFromFunction(SI);
10876 ++NumCombined;
10877 return 0;
10878 }
10879
10880 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10881 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10882 GEP->getOperand(0)->hasOneUse()) {
10883 EraseInstFromFunction(SI);
10884 ++NumCombined;
10885 return 0;
10886 }
10887 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010888
Dan Gohman9941f742007-07-20 16:34:21 +000010889 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010890 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10891 if (KnownAlign >
10892 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10893 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010894 SI.setAlignment(KnownAlign);
10895
Chris Lattner9ca96412006-02-08 03:25:32 +000010896 // Do really simple DSE, to catch cases where there are several consequtive
10897 // stores to the same location, separated by a few arithmetic operations. This
10898 // situation often occurs with bitfield accesses.
10899 BasicBlock::iterator BBI = &SI;
10900 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10901 --ScanInsts) {
10902 --BBI;
10903
10904 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10905 // Prev store isn't volatile, and stores to the same location?
10906 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10907 ++NumDeadStore;
10908 ++BBI;
10909 EraseInstFromFunction(*PrevSI);
10910 continue;
10911 }
10912 break;
10913 }
10914
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010915 // If this is a load, we have to stop. However, if the loaded value is from
10916 // the pointer we're loading and is producing the pointer we're storing,
10917 // then *this* store is dead (X = load P; store X -> P).
10918 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010919 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010920 EraseInstFromFunction(SI);
10921 ++NumCombined;
10922 return 0;
10923 }
10924 // Otherwise, this is a load from some other location. Stores before it
10925 // may not be dead.
10926 break;
10927 }
10928
Chris Lattner9ca96412006-02-08 03:25:32 +000010929 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010930 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010931 break;
10932 }
10933
10934
10935 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010936
10937 // store X, null -> turns into 'unreachable' in SimplifyCFG
10938 if (isa<ConstantPointerNull>(Ptr)) {
10939 if (!isa<UndefValue>(Val)) {
10940 SI.setOperand(0, UndefValue::get(Val->getType()));
10941 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010942 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010943 ++NumCombined;
10944 }
10945 return 0; // Do not modify these!
10946 }
10947
10948 // store undef, Ptr -> noop
10949 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010950 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010951 ++NumCombined;
10952 return 0;
10953 }
10954
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010955 // If the pointer destination is a cast, see if we can fold the cast into the
10956 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010957 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010958 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10959 return Res;
10960 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010961 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010962 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10963 return Res;
10964
Chris Lattner408902b2005-09-12 23:23:25 +000010965
10966 // If this store is the last instruction in the basic block, and if the block
10967 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010968 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010969 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010970 if (BI->isUnconditional())
10971 if (SimplifyStoreAtEndOfBlock(SI))
10972 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010973
Chris Lattner2f503e62005-01-31 05:36:43 +000010974 return 0;
10975}
10976
Chris Lattner3284d1f2007-04-15 00:07:55 +000010977/// SimplifyStoreAtEndOfBlock - Turn things like:
10978/// if () { *P = v1; } else { *P = v2 }
10979/// into a phi node with a store in the successor.
10980///
Chris Lattner31755a02007-04-15 01:02:18 +000010981/// Simplify things like:
10982/// *P = v1; if () { *P = v2; }
10983/// into a phi node with a store in the successor.
10984///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010985bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10986 BasicBlock *StoreBB = SI.getParent();
10987
10988 // Check to see if the successor block has exactly two incoming edges. If
10989 // so, see if the other predecessor contains a store to the same location.
10990 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010991 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010992
10993 // Determine whether Dest has exactly two predecessors and, if so, compute
10994 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010995 pred_iterator PI = pred_begin(DestBB);
10996 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010997 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010998 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010999 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011000 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011001 return false;
11002
11003 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011004 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011005 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011006 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011007 }
Chris Lattner31755a02007-04-15 01:02:18 +000011008 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011009 return false;
11010
11011
Chris Lattner31755a02007-04-15 01:02:18 +000011012 // Verify that the other block ends in a branch and is not otherwise empty.
11013 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011014 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011015 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011016 return false;
11017
Chris Lattner31755a02007-04-15 01:02:18 +000011018 // If the other block ends in an unconditional branch, check for the 'if then
11019 // else' case. there is an instruction before the branch.
11020 StoreInst *OtherStore = 0;
11021 if (OtherBr->isUnconditional()) {
11022 // If this isn't a store, or isn't a store to the same location, bail out.
11023 --BBI;
11024 OtherStore = dyn_cast<StoreInst>(BBI);
11025 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11026 return false;
11027 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011028 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011029 // destinations is StoreBB, then we have the if/then case.
11030 if (OtherBr->getSuccessor(0) != StoreBB &&
11031 OtherBr->getSuccessor(1) != StoreBB)
11032 return false;
11033
11034 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011035 // if/then triangle. See if there is a store to the same ptr as SI that
11036 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011037 for (;; --BBI) {
11038 // Check to see if we find the matching store.
11039 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11040 if (OtherStore->getOperand(1) != SI.getOperand(1))
11041 return false;
11042 break;
11043 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011044 // If we find something that may be using the stored value, or if we run
11045 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011046 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11047 BBI == OtherBB->begin())
11048 return false;
11049 }
11050
11051 // In order to eliminate the store in OtherBr, we have to
11052 // make sure nothing reads the stored value in StoreBB.
11053 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11054 // FIXME: This should really be AA driven.
11055 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11056 return false;
11057 }
11058 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011059
Chris Lattner31755a02007-04-15 01:02:18 +000011060 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011061 Value *MergedVal = OtherStore->getOperand(0);
11062 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011063 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011064 PN->reserveOperandSpace(2);
11065 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011066 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11067 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011068 }
11069
11070 // Advance to a place where it is safe to insert the new store and
11071 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000011072 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011073 while (isa<PHINode>(BBI)) ++BBI;
11074 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11075 OtherStore->isVolatile()), *BBI);
11076
11077 // Nuke the old stores.
11078 EraseInstFromFunction(SI);
11079 EraseInstFromFunction(*OtherStore);
11080 ++NumCombined;
11081 return true;
11082}
11083
Chris Lattner2f503e62005-01-31 05:36:43 +000011084
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011085Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11086 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011087 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011088 BasicBlock *TrueDest;
11089 BasicBlock *FalseDest;
11090 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11091 !isa<Constant>(X)) {
11092 // Swap Destinations and condition...
11093 BI.setCondition(X);
11094 BI.setSuccessor(0, FalseDest);
11095 BI.setSuccessor(1, TrueDest);
11096 return &BI;
11097 }
11098
Reid Spencere4d87aa2006-12-23 06:05:41 +000011099 // Cannonicalize fcmp_one -> fcmp_oeq
11100 FCmpInst::Predicate FPred; Value *Y;
11101 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11102 TrueDest, FalseDest)))
11103 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11104 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11105 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011106 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011107 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11108 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011109 // Swap Destinations and condition...
11110 BI.setCondition(NewSCC);
11111 BI.setSuccessor(0, FalseDest);
11112 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011113 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011114 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011115 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011116 return &BI;
11117 }
11118
11119 // Cannonicalize icmp_ne -> icmp_eq
11120 ICmpInst::Predicate IPred;
11121 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11122 TrueDest, FalseDest)))
11123 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11124 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11125 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11126 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011127 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011128 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11129 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011130 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011131 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011132 BI.setSuccessor(0, FalseDest);
11133 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011134 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011135 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011136 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011137 return &BI;
11138 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011139
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011140 return 0;
11141}
Chris Lattner0864acf2002-11-04 16:18:53 +000011142
Chris Lattner46238a62004-07-03 00:26:11 +000011143Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11144 Value *Cond = SI.getCondition();
11145 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11146 if (I->getOpcode() == Instruction::Add)
11147 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11148 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11149 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011150 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011151 AddRHS));
11152 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011153 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011154 return &SI;
11155 }
11156 }
11157 return 0;
11158}
11159
Chris Lattner220b0cf2006-03-05 00:22:33 +000011160/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11161/// is to leave as a vector operation.
11162static bool CheapToScalarize(Value *V, bool isConstant) {
11163 if (isa<ConstantAggregateZero>(V))
11164 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011165 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011166 if (isConstant) return true;
11167 // If all elts are the same, we can extract.
11168 Constant *Op0 = C->getOperand(0);
11169 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11170 if (C->getOperand(i) != Op0)
11171 return false;
11172 return true;
11173 }
11174 Instruction *I = dyn_cast<Instruction>(V);
11175 if (!I) return false;
11176
11177 // Insert element gets simplified to the inserted element or is deleted if
11178 // this is constant idx extract element and its a constant idx insertelt.
11179 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11180 isa<ConstantInt>(I->getOperand(2)))
11181 return true;
11182 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11183 return true;
11184 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11185 if (BO->hasOneUse() &&
11186 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11187 CheapToScalarize(BO->getOperand(1), isConstant)))
11188 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011189 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11190 if (CI->hasOneUse() &&
11191 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11192 CheapToScalarize(CI->getOperand(1), isConstant)))
11193 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011194
11195 return false;
11196}
11197
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011198/// Read and decode a shufflevector mask.
11199///
11200/// It turns undef elements into values that are larger than the number of
11201/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011202static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11203 unsigned NElts = SVI->getType()->getNumElements();
11204 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11205 return std::vector<unsigned>(NElts, 0);
11206 if (isa<UndefValue>(SVI->getOperand(2)))
11207 return std::vector<unsigned>(NElts, 2*NElts);
11208
11209 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011210 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011211 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11212 if (isa<UndefValue>(CP->getOperand(i)))
11213 Result.push_back(NElts*2); // undef -> 8
11214 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011215 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011216 return Result;
11217}
11218
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011219/// FindScalarElement - Given a vector and an element number, see if the scalar
11220/// value is already around as a register, for example if it were inserted then
11221/// extracted from the vector.
11222static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011223 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11224 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011225 unsigned Width = PTy->getNumElements();
11226 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011227 return UndefValue::get(PTy->getElementType());
11228
11229 if (isa<UndefValue>(V))
11230 return UndefValue::get(PTy->getElementType());
11231 else if (isa<ConstantAggregateZero>(V))
11232 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011233 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011234 return CP->getOperand(EltNo);
11235 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11236 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011237 if (!isa<ConstantInt>(III->getOperand(2)))
11238 return 0;
11239 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011240
11241 // If this is an insert to the element we are looking for, return the
11242 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011243 if (EltNo == IIElt)
11244 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011245
11246 // Otherwise, the insertelement doesn't modify the value, recurse on its
11247 // vector input.
11248 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011249 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011250 unsigned InEl = getShuffleMask(SVI)[EltNo];
11251 if (InEl < Width)
11252 return FindScalarElement(SVI->getOperand(0), InEl);
11253 else if (InEl < Width*2)
11254 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11255 else
11256 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011257 }
11258
11259 // Otherwise, we don't know.
11260 return 0;
11261}
11262
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011263Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011264
Dan Gohman07a96762007-07-16 14:29:03 +000011265 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011266 if (isa<UndefValue>(EI.getOperand(0)))
11267 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11268
Dan Gohman07a96762007-07-16 14:29:03 +000011269 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011270 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11271 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11272
Reid Spencer9d6565a2007-02-15 02:26:10 +000011273 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011274 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011275 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011276 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011277 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011278 if (C->getOperand(i) != op0) {
11279 op0 = 0;
11280 break;
11281 }
11282 if (op0)
11283 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011284 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011285
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011286 // If extracting a specified index from the vector, see if we can recursively
11287 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011288 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011289 unsigned IndexVal = IdxC->getZExtValue();
11290 unsigned VectorWidth =
11291 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11292
11293 // If this is extracting an invalid index, turn this into undef, to avoid
11294 // crashing the code below.
11295 if (IndexVal >= VectorWidth)
11296 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11297
Chris Lattner867b99f2006-10-05 06:55:50 +000011298 // This instruction only demands the single element from the input vector.
11299 // If the input vector has a single use, simplify it based on this use
11300 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011301 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011302 uint64_t UndefElts;
11303 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011304 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011305 UndefElts)) {
11306 EI.setOperand(0, V);
11307 return &EI;
11308 }
11309 }
11310
Reid Spencerb83eb642006-10-20 07:07:24 +000011311 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011312 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011313
11314 // If the this extractelement is directly using a bitcast from a vector of
11315 // the same number of elements, see if we can find the source element from
11316 // it. In this case, we will end up needing to bitcast the scalars.
11317 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11318 if (const VectorType *VT =
11319 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11320 if (VT->getNumElements() == VectorWidth)
11321 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11322 return new BitCastInst(Elt, EI.getType());
11323 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011324 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011325
Chris Lattner73fa49d2006-05-25 22:53:38 +000011326 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011327 if (I->hasOneUse()) {
11328 // Push extractelement into predecessor operation if legal and
11329 // profitable to do so
11330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011331 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11332 if (CheapToScalarize(BO, isConstantElt)) {
11333 ExtractElementInst *newEI0 =
11334 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11335 EI.getName()+".lhs");
11336 ExtractElementInst *newEI1 =
11337 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11338 EI.getName()+".rhs");
11339 InsertNewInstBefore(newEI0, EI);
11340 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011341 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011342 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011343 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011344 unsigned AS =
11345 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011346 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11347 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011348 GetElementPtrInst *GEP =
11349 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011350 InsertNewInstBefore(GEP, EI);
11351 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011352 }
11353 }
11354 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11355 // Extracting the inserted element?
11356 if (IE->getOperand(2) == EI.getOperand(1))
11357 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11358 // If the inserted and extracted elements are constants, they must not
11359 // be the same value, extract from the pre-inserted value instead.
11360 if (isa<Constant>(IE->getOperand(2)) &&
11361 isa<Constant>(EI.getOperand(1))) {
11362 AddUsesToWorkList(EI);
11363 EI.setOperand(0, IE->getOperand(0));
11364 return &EI;
11365 }
11366 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11367 // If this is extracting an element from a shufflevector, figure out where
11368 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011369 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11370 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011371 Value *Src;
11372 if (SrcIdx < SVI->getType()->getNumElements())
11373 Src = SVI->getOperand(0);
11374 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11375 SrcIdx -= SVI->getType()->getNumElements();
11376 Src = SVI->getOperand(1);
11377 } else {
11378 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011379 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011380 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011381 }
11382 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011383 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011384 return 0;
11385}
11386
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011387/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11388/// elements from either LHS or RHS, return the shuffle mask and true.
11389/// Otherwise, return false.
11390static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11391 std::vector<Constant*> &Mask) {
11392 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11393 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011394 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011395
11396 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011397 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011398 return true;
11399 } else if (V == LHS) {
11400 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011401 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011402 return true;
11403 } else if (V == RHS) {
11404 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011405 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011406 return true;
11407 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11408 // If this is an insert of an extract from some other vector, include it.
11409 Value *VecOp = IEI->getOperand(0);
11410 Value *ScalarOp = IEI->getOperand(1);
11411 Value *IdxOp = IEI->getOperand(2);
11412
Chris Lattnerd929f062006-04-27 21:14:21 +000011413 if (!isa<ConstantInt>(IdxOp))
11414 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011415 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011416
11417 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11418 // Okay, we can handle this if the vector we are insertinting into is
11419 // transitively ok.
11420 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11421 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011422 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011423 return true;
11424 }
11425 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11426 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011427 EI->getOperand(0)->getType() == V->getType()) {
11428 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011429 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011430
11431 // This must be extracting from either LHS or RHS.
11432 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11433 // Okay, we can handle this if the vector we are insertinting into is
11434 // transitively ok.
11435 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11436 // If so, update the mask to reflect the inserted value.
11437 if (EI->getOperand(0) == LHS) {
11438 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011439 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011440 } else {
11441 assert(EI->getOperand(0) == RHS);
11442 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011443 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011444
11445 }
11446 return true;
11447 }
11448 }
11449 }
11450 }
11451 }
11452 // TODO: Handle shufflevector here!
11453
11454 return false;
11455}
11456
11457/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11458/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11459/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011460static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011461 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011462 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011463 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011464 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011465 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011466
11467 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011468 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011469 return V;
11470 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011471 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011472 return V;
11473 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11474 // If this is an insert of an extract from some other vector, include it.
11475 Value *VecOp = IEI->getOperand(0);
11476 Value *ScalarOp = IEI->getOperand(1);
11477 Value *IdxOp = IEI->getOperand(2);
11478
11479 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11480 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11481 EI->getOperand(0)->getType() == V->getType()) {
11482 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011483 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11484 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011485
11486 // Either the extracted from or inserted into vector must be RHSVec,
11487 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011488 if (EI->getOperand(0) == RHS || RHS == 0) {
11489 RHS = EI->getOperand(0);
11490 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011491 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011492 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011493 return V;
11494 }
11495
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011496 if (VecOp == RHS) {
11497 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011498 // Everything but the extracted element is replaced with the RHS.
11499 for (unsigned i = 0; i != NumElts; ++i) {
11500 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011501 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011502 }
11503 return V;
11504 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011505
11506 // If this insertelement is a chain that comes from exactly these two
11507 // vectors, return the vector and the effective shuffle.
11508 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11509 return EI->getOperand(0);
11510
Chris Lattnerefb47352006-04-15 01:39:45 +000011511 }
11512 }
11513 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011514 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011515
11516 // Otherwise, can't do anything fancy. Return an identity vector.
11517 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011518 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011519 return V;
11520}
11521
11522Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11523 Value *VecOp = IE.getOperand(0);
11524 Value *ScalarOp = IE.getOperand(1);
11525 Value *IdxOp = IE.getOperand(2);
11526
Chris Lattner599ded12007-04-09 01:11:16 +000011527 // Inserting an undef or into an undefined place, remove this.
11528 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11529 ReplaceInstUsesWith(IE, VecOp);
11530
Chris Lattnerefb47352006-04-15 01:39:45 +000011531 // If the inserted element was extracted from some other vector, and if the
11532 // indexes are constant, try to turn this into a shufflevector operation.
11533 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11534 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11535 EI->getOperand(0)->getType() == IE.getType()) {
11536 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011537 unsigned ExtractedIdx =
11538 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011539 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011540
11541 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11542 return ReplaceInstUsesWith(IE, VecOp);
11543
11544 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11545 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11546
11547 // If we are extracting a value from a vector, then inserting it right
11548 // back into the same place, just use the input vector.
11549 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11550 return ReplaceInstUsesWith(IE, VecOp);
11551
11552 // We could theoretically do this for ANY input. However, doing so could
11553 // turn chains of insertelement instructions into a chain of shufflevector
11554 // instructions, and right now we do not merge shufflevectors. As such,
11555 // only do this in a situation where it is clear that there is benefit.
11556 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11557 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11558 // the values of VecOp, except then one read from EIOp0.
11559 // Build a new shuffle mask.
11560 std::vector<Constant*> Mask;
11561 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011562 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011563 else {
11564 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011565 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011566 NumVectorElts));
11567 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011568 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011569 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011570 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011571 }
11572
11573 // If this insertelement isn't used by some other insertelement, turn it
11574 // (and any insertelements it points to), into one big shuffle.
11575 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11576 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011577 Value *RHS = 0;
11578 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11579 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11580 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011581 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011582 }
11583 }
11584 }
11585
11586 return 0;
11587}
11588
11589
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011590Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11591 Value *LHS = SVI.getOperand(0);
11592 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011593 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011594
11595 bool MadeChange = false;
11596
Chris Lattner867b99f2006-10-05 06:55:50 +000011597 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011598 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011599 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11600
Chris Lattnere4929dd2007-01-05 07:36:08 +000011601 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011602 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011603 if (isa<UndefValue>(SVI.getOperand(1))) {
11604 // Scan to see if there are any references to the RHS. If so, replace them
11605 // with undef element refs and set MadeChange to true.
11606 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11607 if (Mask[i] >= e && Mask[i] != 2*e) {
11608 Mask[i] = 2*e;
11609 MadeChange = true;
11610 }
11611 }
11612
11613 if (MadeChange) {
11614 // Remap any references to RHS to use LHS.
11615 std::vector<Constant*> Elts;
11616 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11617 if (Mask[i] == 2*e)
11618 Elts.push_back(UndefValue::get(Type::Int32Ty));
11619 else
11620 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11621 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011622 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011623 }
11624 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011625
Chris Lattner863bcff2006-05-25 23:48:38 +000011626 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11627 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11628 if (LHS == RHS || isa<UndefValue>(LHS)) {
11629 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011630 // shuffle(undef,undef,mask) -> undef.
11631 return ReplaceInstUsesWith(SVI, LHS);
11632 }
11633
Chris Lattner863bcff2006-05-25 23:48:38 +000011634 // Remap any references to RHS to use LHS.
11635 std::vector<Constant*> Elts;
11636 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011637 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011638 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011639 else {
11640 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11641 (Mask[i] < e && isa<UndefValue>(LHS)))
11642 Mask[i] = 2*e; // Turn into undef.
11643 else
11644 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011645 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011646 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011647 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011648 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011649 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011650 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011651 LHS = SVI.getOperand(0);
11652 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011653 MadeChange = true;
11654 }
11655
Chris Lattner7b2e27922006-05-26 00:29:06 +000011656 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011657 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011658
Chris Lattner863bcff2006-05-25 23:48:38 +000011659 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11660 if (Mask[i] >= e*2) continue; // Ignore undef values.
11661 // Is this an identity shuffle of the LHS value?
11662 isLHSID &= (Mask[i] == i);
11663
11664 // Is this an identity shuffle of the RHS value?
11665 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011666 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011667
Chris Lattner863bcff2006-05-25 23:48:38 +000011668 // Eliminate identity shuffles.
11669 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11670 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011671
Chris Lattner7b2e27922006-05-26 00:29:06 +000011672 // If the LHS is a shufflevector itself, see if we can combine it with this
11673 // one without producing an unusual shuffle. Here we are really conservative:
11674 // we are absolutely afraid of producing a shuffle mask not in the input
11675 // program, because the code gen may not be smart enough to turn a merged
11676 // shuffle into two specific shuffles: it may produce worse code. As such,
11677 // we only merge two shuffles if the result is one of the two input shuffle
11678 // masks. In this case, merging the shuffles just removes one instruction,
11679 // which we know is safe. This is good for things like turning:
11680 // (splat(splat)) -> splat.
11681 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11682 if (isa<UndefValue>(RHS)) {
11683 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11684
11685 std::vector<unsigned> NewMask;
11686 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11687 if (Mask[i] >= 2*e)
11688 NewMask.push_back(2*e);
11689 else
11690 NewMask.push_back(LHSMask[Mask[i]]);
11691
11692 // If the result mask is equal to the src shuffle or this shuffle mask, do
11693 // the replacement.
11694 if (NewMask == LHSMask || NewMask == Mask) {
11695 std::vector<Constant*> Elts;
11696 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11697 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011698 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011699 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011700 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011701 }
11702 }
11703 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11704 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011705 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011706 }
11707 }
11708 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011709
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011710 return MadeChange ? &SVI : 0;
11711}
11712
11713
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011714
Chris Lattnerea1c4542004-12-08 23:43:58 +000011715
11716/// TryToSinkInstruction - Try to move the specified instruction from its
11717/// current block into the beginning of DestBlock, which can only happen if it's
11718/// safe to move the instruction past all of the instructions between it and the
11719/// end of its block.
11720static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11721 assert(I->hasOneUse() && "Invariants didn't hold!");
11722
Chris Lattner108e9022005-10-27 17:13:11 +000011723 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011724 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11725 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011726
Chris Lattnerea1c4542004-12-08 23:43:58 +000011727 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011728 if (isa<AllocaInst>(I) && I->getParent() ==
11729 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011730 return false;
11731
Chris Lattner96a52a62004-12-09 07:14:34 +000011732 // We can only sink load instructions if there is nothing between the load and
11733 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011734 if (I->mayReadFromMemory()) {
11735 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011736 Scan != E; ++Scan)
11737 if (Scan->mayWriteToMemory())
11738 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011739 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011740
11741 BasicBlock::iterator InsertPos = DestBlock->begin();
11742 while (isa<PHINode>(InsertPos)) ++InsertPos;
11743
Chris Lattner4bc5f802005-08-08 19:11:57 +000011744 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011745 ++NumSunkInst;
11746 return true;
11747}
11748
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011749
11750/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11751/// all reachable code to the worklist.
11752///
11753/// This has a couple of tricks to make the code faster and more powerful. In
11754/// particular, we constant fold and DCE instructions as we go, to avoid adding
11755/// them to the worklist (this significantly speeds up instcombine on code where
11756/// many instructions are dead or constant). Additionally, if we find a branch
11757/// whose condition is a known constant, we only visit the reachable successors.
11758///
11759static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011760 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011761 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011762 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011763 std::vector<BasicBlock*> Worklist;
11764 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011765
Chris Lattner2c7718a2007-03-23 19:17:18 +000011766 while (!Worklist.empty()) {
11767 BB = Worklist.back();
11768 Worklist.pop_back();
11769
11770 // We have now visited this block! If we've already been here, ignore it.
11771 if (!Visited.insert(BB)) continue;
11772
11773 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11774 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011775
Chris Lattner2c7718a2007-03-23 19:17:18 +000011776 // DCE instruction if trivially dead.
11777 if (isInstructionTriviallyDead(Inst)) {
11778 ++NumDeadInst;
11779 DOUT << "IC: DCE: " << *Inst;
11780 Inst->eraseFromParent();
11781 continue;
11782 }
11783
11784 // ConstantProp instruction if trivially constant.
11785 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11786 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11787 Inst->replaceAllUsesWith(C);
11788 ++NumConstProp;
11789 Inst->eraseFromParent();
11790 continue;
11791 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011792
Chris Lattner2c7718a2007-03-23 19:17:18 +000011793 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011794 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011795
11796 // Recursively visit successors. If this is a branch or switch on a
11797 // constant, only visit the reachable successor.
11798 TerminatorInst *TI = BB->getTerminator();
11799 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11800 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11801 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011802 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011803 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011804 continue;
11805 }
11806 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11807 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11808 // See if this is an explicit destination.
11809 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11810 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011811 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011812 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011813 continue;
11814 }
11815
11816 // Otherwise it is the default destination.
11817 Worklist.push_back(SI->getSuccessor(0));
11818 continue;
11819 }
11820 }
11821
11822 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11823 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011824 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011825}
11826
Chris Lattnerec9c3582007-03-03 02:04:50 +000011827bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011828 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011829 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011830
11831 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11832 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011833
Chris Lattnerb3d59702005-07-07 20:40:38 +000011834 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011835 // Do a depth-first traversal of the function, populate the worklist with
11836 // the reachable instructions. Ignore blocks that are not reachable. Keep
11837 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011838 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011839 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011840
Chris Lattnerb3d59702005-07-07 20:40:38 +000011841 // Do a quick scan over the function. If we find any blocks that are
11842 // unreachable, remove any instructions inside of them. This prevents
11843 // the instcombine code from having to deal with some bad special cases.
11844 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11845 if (!Visited.count(BB)) {
11846 Instruction *Term = BB->getTerminator();
11847 while (Term != BB->begin()) { // Remove instrs bottom-up
11848 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011849
Bill Wendlingb7427032006-11-26 09:46:52 +000011850 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011851 ++NumDeadInst;
11852
11853 if (!I->use_empty())
11854 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11855 I->eraseFromParent();
11856 }
11857 }
11858 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011859
Chris Lattnerdbab3862007-03-02 21:28:56 +000011860 while (!Worklist.empty()) {
11861 Instruction *I = RemoveOneFromWorkList();
11862 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011863
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011864 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011865 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011866 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011867 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011868 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011869 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011870
Bill Wendlingb7427032006-11-26 09:46:52 +000011871 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011872
11873 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011874 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011875 continue;
11876 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011877
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011878 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011879 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011880 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011881
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011882 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011883 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011884 ReplaceInstUsesWith(*I, C);
11885
Chris Lattner62b14df2002-09-02 04:59:56 +000011886 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011887 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011888 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011889 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011890 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011891
Chris Lattnerea1c4542004-12-08 23:43:58 +000011892 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011893 // FIXME: Remove GetResultInst test when first class support for aggregates
11894 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011895 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011896 BasicBlock *BB = I->getParent();
11897 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11898 if (UserParent != BB) {
11899 bool UserIsSuccessor = false;
11900 // See if the user is one of our successors.
11901 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11902 if (*SI == UserParent) {
11903 UserIsSuccessor = true;
11904 break;
11905 }
11906
11907 // If the user is one of our immediate successors, and if that successor
11908 // only has us as a predecessors (we'd have to split the critical edge
11909 // otherwise), we can keep going.
11910 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11911 next(pred_begin(UserParent)) == pred_end(UserParent))
11912 // Okay, the CFG is simple enough, try to sink this instruction.
11913 Changed |= TryToSinkInstruction(I, UserParent);
11914 }
11915 }
11916
Chris Lattner8a2a3112001-12-14 16:52:21 +000011917 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011918#ifndef NDEBUG
11919 std::string OrigI;
11920#endif
11921 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011922 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011923 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011924 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011925 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011926 DOUT << "IC: Old = " << *I
11927 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011928
Chris Lattnerf523d062004-06-09 05:08:07 +000011929 // Everything uses the new instruction now.
11930 I->replaceAllUsesWith(Result);
11931
11932 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011933 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011934 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011935
Chris Lattner6934a042007-02-11 01:23:03 +000011936 // Move the name to the new instruction first.
11937 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011938
11939 // Insert the new instruction into the basic block...
11940 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011941 BasicBlock::iterator InsertPos = I;
11942
11943 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11944 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11945 ++InsertPos;
11946
11947 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011948
Chris Lattner00d51312004-05-01 23:27:23 +000011949 // Make sure that we reprocess all operands now that we reduced their
11950 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011951 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011952
Chris Lattnerf523d062004-06-09 05:08:07 +000011953 // Instructions can end up on the worklist more than once. Make sure
11954 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011955 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011956
11957 // Erase the old instruction.
11958 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011959 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011960#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011961 DOUT << "IC: Mod = " << OrigI
11962 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011963#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011964
Chris Lattner90ac28c2002-08-02 19:29:35 +000011965 // If the instruction was modified, it's possible that it is now dead.
11966 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011967 if (isInstructionTriviallyDead(I)) {
11968 // Make sure we process all operands now that we are reducing their
11969 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011970 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011971
Chris Lattner00d51312004-05-01 23:27:23 +000011972 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011973 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011974 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011975 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011976 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011977 AddToWorkList(I);
11978 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011979 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011980 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011981 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011982 }
11983 }
11984
Chris Lattnerec9c3582007-03-03 02:04:50 +000011985 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011986
11987 // Do an explicit clear, this shrinks the map if needed.
11988 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011989 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011990}
11991
Chris Lattnerec9c3582007-03-03 02:04:50 +000011992
11993bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011994 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11995
Chris Lattnerec9c3582007-03-03 02:04:50 +000011996 bool EverMadeChange = false;
11997
11998 // Iterate while there is work to do.
11999 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012000 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012001 EverMadeChange = true;
12002 return EverMadeChange;
12003}
12004
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012005FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012006 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012007}
Brian Gaeked0fde302003-11-11 22:41:34 +000012008