blob: d7f5ccf788434c9e182b55133a0fe50ba71e1067 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000060#include <climits>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194 Instruction *LHS,
195 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000198
Reid Spencere4d87aa2006-12-23 06:05:41 +0000199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000202 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000205 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000209 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000210 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000216 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000217 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000220 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000225 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000226 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000227 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000228 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000229 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000230 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000231 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000234
235 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000236 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000237
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000239 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000241 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000244 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000245
Chris Lattner28977af2004-04-05 01:30:19 +0000246 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000247 // InsertNewInstBefore - insert an instruction New before instruction Old
248 // in the program. Add the new instruction to the worklist.
249 //
Chris Lattner955f3312004-09-28 21:48:02 +0000250 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000251 assert(New && New->getParent() == 0 &&
252 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000253 BasicBlock *BB = Old.getParent();
254 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000255 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000256 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000257 }
258
Chris Lattner0c967662004-09-24 15:21:34 +0000259 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260 /// This also adds the cast to the worklist. Finally, this returns the
261 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000262 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
263 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000264 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000265
Chris Lattnere2ed0572006-04-06 19:19:17 +0000266 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000267 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000268
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000269 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000270 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000271 return C;
272 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000273
274 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
276 }
277
Chris Lattner0c967662004-09-24 15:21:34 +0000278
Chris Lattner8b170942002-08-09 23:47:40 +0000279 // ReplaceInstUsesWith - This method is to be used when an instruction is
280 // found to be dead, replacable with another preexisting expression. Here
281 // we add all uses of I to the worklist, replace all uses of I with the new
282 // value, then return I, so that the inst combiner will know that I was
283 // modified.
284 //
285 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000286 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000287 if (&I != V) {
288 I.replaceAllUsesWith(V);
289 return &I;
290 } else {
291 // If we are replacing the instruction with itself, this must be in a
292 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000293 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000294 return &I;
295 }
Chris Lattner8b170942002-08-09 23:47:40 +0000296 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000297
Chris Lattner6dce1a72006-02-07 06:56:34 +0000298 // UpdateValueUsesWith - This method is to be used when an value is
299 // found to be replacable with another preexisting expression or was
300 // updated. Here we add all uses of I to the worklist, replace all uses of
301 // I with the new value (unless the instruction was just updated), then
302 // return true, so that the inst combiner will know that I was modified.
303 //
304 bool UpdateValueUsesWith(Value *Old, Value *New) {
305 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
306 if (Old != New)
307 Old->replaceAllUsesWith(New);
308 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000309 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000310 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000311 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000312 return true;
313 }
314
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
318 // this function.
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000322 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000323 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000324 return 0; // Don't do anything with FI
325 }
326
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000327 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000328 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329 /// InsertBefore instruction. This is specialized a bit to avoid inserting
330 /// casts that are known to not do anything...
331 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000332 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000334 Instruction *InsertBefore);
335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000338 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000339
Reid Spencere4d87aa2006-12-23 06:05:41 +0000340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
343
Reid Spencer2ec619a2007-03-23 21:24:59 +0000344 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000346 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
348 unsigned Depth = 0);
349
Chris Lattner867b99f2006-10-05 06:55:50 +0000350 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351 uint64_t &UndefElts, unsigned Depth = 0);
352
Chris Lattner4e998b22004-09-29 05:07:12 +0000353 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354 // PHI node as operand #0, see if we can fold the instruction into the PHI
355 // (which is only possible if all operands to the PHI are constants).
356 Instruction *FoldOpIntoPhi(Instruction &I);
357
Chris Lattnerbac32862004-11-14 19:13:23 +0000358 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359 // operator and they all are only used by the PHI, PHI together their
360 // inputs, and do the operation once, to the result of the PHI.
361 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000362 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
363
364
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000365 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000367
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000368 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000369 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000370 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000371 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000372 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000373 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000374 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000375 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000376 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000377
Chris Lattnerafe91a52006-06-15 19:07:26 +0000378
Reid Spencerc55b2432006-12-13 18:21:21 +0000379 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000380
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000381 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Dan Gohman45b4e482008-05-19 22:14:15 +0000382 APInt& KnownOne, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000383 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
Dan Gohman45b4e482008-05-19 22:14:15 +0000384 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000385 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
386 unsigned CastOpc,
387 int &NumCastsRemoved);
388 unsigned GetOrEnforceKnownAlignment(Value *V,
389 unsigned PrefAlign = 0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000390 };
391}
392
Dan Gohman844731a2008-05-13 00:00:25 +0000393char InstCombiner::ID = 0;
394static RegisterPass<InstCombiner>
395X("instcombine", "Combine redundant instructions");
396
Chris Lattner4f98c562003-03-10 21:43:22 +0000397// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000398// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000399static unsigned getComplexity(Value *V) {
400 if (isa<Instruction>(V)) {
401 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000402 return 3;
403 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000404 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000405 if (isa<Argument>(V)) return 3;
406 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000407}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000408
Chris Lattnerc8802d22003-03-11 00:12:48 +0000409// isOnlyUse - Return true if this instruction will be deleted if we stop using
410// it.
411static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000412 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000413}
414
Chris Lattner4cb170c2004-02-23 06:38:22 +0000415// getPromotedType - Return the specified type promoted as it would be to pass
416// though a va_arg area...
417static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000418 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419 if (ITy->getBitWidth() < 32)
420 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000421 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000422 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000423}
424
Reid Spencer3da59db2006-11-27 01:05:10 +0000425/// getBitCastOperand - If the specified operand is a CastInst or a constant
426/// expression bitcast, return the operand value, otherwise return null.
427static Value *getBitCastOperand(Value *V) {
428 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000429 return I->getOperand(0);
430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000431 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000432 return CE->getOperand(0);
433 return 0;
434}
435
Reid Spencer3da59db2006-11-27 01:05:10 +0000436/// This function is a wrapper around CastInst::isEliminableCastPair. It
437/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000438static Instruction::CastOps
439isEliminableCastPair(
440 const CastInst *CI, ///< The first cast instruction
441 unsigned opcode, ///< The opcode of the second cast instruction
442 const Type *DstTy, ///< The target type for the second cast instruction
443 TargetData *TD ///< The target data for pointer size
444) {
445
446 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
447 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000448
Reid Spencer3da59db2006-11-27 01:05:10 +0000449 // Get the opcodes of the two Cast instructions
450 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000452
Reid Spencer3da59db2006-11-27 01:05:10 +0000453 return Instruction::CastOps(
454 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000456}
457
458/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459/// in any code being generated. It does not require codegen if V is simple
460/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000461static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
462 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000463 if (V->getType() == Ty || isa<Constant>(V)) return false;
464
Chris Lattner01575b72006-05-25 23:24:33 +0000465 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000466 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000467 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000468 return false;
469 return true;
470}
471
472/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473/// InsertBefore instruction. This is specialized a bit to avoid inserting
474/// casts that are known to not do anything...
475///
Reid Spencer17212df2006-12-12 09:18:51 +0000476Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000478 Instruction *InsertBefore) {
479 if (V->getType() == DestTy) return V;
480 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000481 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000482
Reid Spencer17212df2006-12-12 09:18:51 +0000483 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000484}
485
Chris Lattner4f98c562003-03-10 21:43:22 +0000486// SimplifyCommutative - This performs a few simplifications for commutative
487// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000488//
Chris Lattner4f98c562003-03-10 21:43:22 +0000489// 1. Order operands such that they are listed from right (least complex) to
490// left (most complex). This puts constants before unary operators before
491// binary operators.
492//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000493// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000495//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000496bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000497 bool Changed = false;
498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000500
Chris Lattner4f98c562003-03-10 21:43:22 +0000501 if (!I.isAssociative()) return Changed;
502 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000506 Constant *Folded = ConstantExpr::get(I.getOpcode(),
507 cast<Constant>(I.getOperand(1)),
508 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000509 I.setOperand(0, Op->getOperand(0));
510 I.setOperand(1, Folded);
511 return true;
512 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514 isOnlyUse(Op) && isOnlyUse(Op1)) {
515 Constant *C1 = cast<Constant>(Op->getOperand(1));
516 Constant *C2 = cast<Constant>(Op1->getOperand(1));
517
518 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000519 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000520 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521 Op1->getOperand(0),
522 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000523 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524 I.setOperand(0, New);
525 I.setOperand(1, Folded);
526 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000527 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000528 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000530}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000531
Reid Spencere4d87aa2006-12-23 06:05:41 +0000532/// SimplifyCompare - For a CmpInst this function just orders the operands
533/// so that theyare listed from right (least complex) to left (most complex).
534/// This puts constants before unary operators before binary operators.
535bool InstCombiner::SimplifyCompare(CmpInst &I) {
536 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
537 return false;
538 I.swapOperands();
539 // Compare instructions are not associative so there's nothing else we can do.
540 return true;
541}
542
Chris Lattner8d969642003-03-10 23:06:50 +0000543// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000545//
Chris Lattner8d969642003-03-10 23:06:50 +0000546static inline Value *dyn_castNegVal(Value *V) {
547 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000548 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000549
Chris Lattner0ce85802004-12-14 20:08:06 +0000550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000553
554 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555 if (C->getType()->getElementType()->isInteger())
556 return ConstantExpr::getNeg(C);
557
Chris Lattner8d969642003-03-10 23:06:50 +0000558 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000559}
560
Chris Lattner8d969642003-03-10 23:06:50 +0000561static inline Value *dyn_castNotVal(Value *V) {
562 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000563 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000564
565 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000566 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000567 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000568 return 0;
569}
570
Chris Lattnerc8802d22003-03-11 00:12:48 +0000571// dyn_castFoldableMul - If this value is a multiply that can be folded into
572// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000573// non-constant operand of the multiply, and set CST to point to the multiplier.
574// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000575//
Chris Lattner50af16a2004-11-13 19:50:12 +0000576static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000577 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000578 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000579 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000580 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000581 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000582 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000583 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000584 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000585 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000586 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000587 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000588 return I->getOperand(0);
589 }
590 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000592}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000593
Chris Lattner574da9b2005-01-13 20:14:25 +0000594/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595/// expression, return it.
596static User *dyn_castGetElementPtr(Value *V) {
597 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599 if (CE->getOpcode() == Instruction::GetElementPtr)
600 return cast<User>(V);
601 return false;
602}
603
Dan Gohmaneee962e2008-04-10 18:43:06 +0000604/// getOpcode - If this is an Instruction or a ConstantExpr, return the
605/// opcode value. Otherwise return UserOp1.
Dan Gohman45b4e482008-05-19 22:14:15 +0000606static unsigned getOpcode(Value *V) {
607 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000608 return I->getOpcode();
Dan Gohman45b4e482008-05-19 22:14:15 +0000609 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohmaneee962e2008-04-10 18:43:06 +0000610 return CE->getOpcode();
611 // Use UserOp1 to mean there's no opcode.
612 return Instruction::UserOp1;
613}
614
Reid Spencer7177c3a2007-03-25 05:33:51 +0000615/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000616static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000617 APInt Val(C->getValue());
618 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000619}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000620/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000621static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000622 APInt Val(C->getValue());
623 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000624}
625/// Add - Add two ConstantInts together
626static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627 return ConstantInt::get(C1->getValue() + C2->getValue());
628}
629/// And - Bitwise AND two ConstantInts together
630static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631 return ConstantInt::get(C1->getValue() & C2->getValue());
632}
633/// Subtract - Subtract one ConstantInt from another
634static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635 return ConstantInt::get(C1->getValue() - C2->getValue());
636}
637/// Multiply - Multiply two ConstantInts together
638static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000640}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000641/// MultiplyOverflows - True if the multiply can not be expressed in an int
642/// this size.
643static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644 uint32_t W = C1->getBitWidth();
645 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646 if (sign) {
647 LHSExt.sext(W * 2);
648 RHSExt.sext(W * 2);
649 } else {
650 LHSExt.zext(W * 2);
651 RHSExt.zext(W * 2);
652 }
653
654 APInt MulExt = LHSExt * RHSExt;
655
656 if (sign) {
657 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659 return MulExt.slt(Min) || MulExt.sgt(Max);
660 } else
661 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662}
Chris Lattner955f3312004-09-28 21:48:02 +0000663
Chris Lattner68d5ff22006-02-09 07:38:58 +0000664/// ComputeMaskedBits - Determine which of the bits specified in Mask are
665/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000666/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
667/// processing.
668/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
669/// we cannot optimize based on the assumption that it is zero without changing
670/// it to be an explicit zero. If we don't change it to zero, other code could
671/// optimized based on the contradictory assumption that it is non-zero.
672/// Because instcombine aggressively folds operations with undef args anyway,
673/// this won't lose us code quality.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000674void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675 APInt& KnownZero, APInt& KnownOne,
Dan Gohman45b4e482008-05-19 22:14:15 +0000676 unsigned Depth) const {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000677 assert(V && "No Value?");
678 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000679 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000680 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681 "Not integer or pointer type!");
682 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683 (!isa<IntegerType>(V->getType()) ||
684 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000685 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000686 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000687 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Dan Gohman45b4e482008-05-19 22:14:15 +0000688
Reid Spencer3e7594f2007-03-08 01:46:38 +0000689 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000691 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000692 KnownZero = ~KnownOne & Mask;
693 return;
694 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000695 // Null is all-zeros.
696 if (isa<ConstantPointerNull>(V)) {
697 KnownOne.clear();
698 KnownZero = Mask;
699 return;
700 }
701 // The address of an aligned GlobalValue has trailing zeros.
702 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703 unsigned Align = GV->getAlignment();
704 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
705 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
706 if (Align > 0)
707 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708 CountTrailingZeros_32(Align));
709 else
710 KnownZero.clear();
711 KnownOne.clear();
712 return;
713 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000714
Dan Gohman23e8b712008-04-28 17:02:21 +0000715 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
716
Reid Spencer3e7594f2007-03-08 01:46:38 +0000717 if (Depth == 6 || Mask == 0)
718 return; // Limit search depth.
719
Dan Gohmaneee962e2008-04-10 18:43:06 +0000720 User *I = dyn_cast<User>(V);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000721 if (!I) return;
722
723 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000724 switch (getOpcode(I)) {
725 default: break;
Reid Spencer2b812072007-03-25 02:03:12 +0000726 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000727 // If either the LHS or the RHS are Zero, the result is zero.
728 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000729 APInt Mask2(Mask & ~KnownZero);
730 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000731 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
732 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
733
734 // Output known-1 bits are only known if set in both the LHS & RHS.
735 KnownOne &= KnownOne2;
736 // Output known-0 are known to be clear if zero in either the LHS | RHS.
737 KnownZero |= KnownZero2;
738 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000739 }
740 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000741 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000742 APInt Mask2(Mask & ~KnownOne);
743 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000744 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746
747 // Output known-0 bits are only known if clear in both the LHS & RHS.
748 KnownZero &= KnownZero2;
749 // Output known-1 are known to be set if set in either the LHS | RHS.
750 KnownOne |= KnownOne2;
751 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000752 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000753 case Instruction::Xor: {
754 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
758
759 // Output known-0 bits are known if clear or set in both the LHS & RHS.
760 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761 // Output known-1 are known to be set if set in only one of the LHS, RHS.
762 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763 KnownZero = KnownZeroOut;
764 return;
765 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000766 case Instruction::Mul: {
767 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
772
773 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohman23e8b712008-04-28 17:02:21 +0000774 // Also compute a conserative estimate for high known-0 bits.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000775 // More trickiness is possible, but this is sufficient for the
776 // interesting case of alignment computation.
777 KnownOne.clear();
778 unsigned TrailZ = KnownZero.countTrailingOnes() +
779 KnownZero2.countTrailingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +0000780 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman42ac9292008-05-07 00:35:55 +0000781 KnownZero2.countLeadingOnes(),
782 BitWidth) - BitWidth;
Dan Gohman23e8b712008-04-28 17:02:21 +0000783
Dan Gohmaneee962e2008-04-10 18:43:06 +0000784 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000785 LeadZ = std::min(LeadZ, BitWidth);
786 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000788 KnownZero &= Mask;
789 return;
790 }
Dan Gohman23e8b712008-04-28 17:02:21 +0000791 case Instruction::UDiv: {
792 // For the purposes of computing leading zeros we can conservatively
793 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1d9cd502008-05-02 21:30:02 +0000794 // be less than the denominator.
Dan Gohman23e8b712008-04-28 17:02:21 +0000795 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796 ComputeMaskedBits(I->getOperand(0),
797 AllOnes, KnownZero2, KnownOne2, Depth+1);
798 unsigned LeadZ = KnownZero2.countLeadingOnes();
799
800 KnownOne2.clear();
801 KnownZero2.clear();
802 ComputeMaskedBits(I->getOperand(1),
803 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1d9cd502008-05-02 21:30:02 +0000804 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805 if (RHSUnknownLeadingOnes != BitWidth)
806 LeadZ = std::min(BitWidth,
807 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000808
809 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
810 return;
811 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000812 case Instruction::Select:
813 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
816 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
817
818 // Only known if known in both the LHS and RHS.
819 KnownOne &= KnownOne2;
820 KnownZero &= KnownZero2;
821 return;
822 case Instruction::FPTrunc:
823 case Instruction::FPExt:
824 case Instruction::FPToUI:
825 case Instruction::FPToSI:
826 case Instruction::SIToFP:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000827 case Instruction::UIToFP:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000828 return; // Can't work with floating point.
829 case Instruction::PtrToInt:
Reid Spencer3e7594f2007-03-08 01:46:38 +0000830 case Instruction::IntToPtr:
Dan Gohmaneee962e2008-04-10 18:43:06 +0000831 // We can't handle these if we don't know the pointer size.
832 if (!TD) return;
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000833 // FALL THROUGH and handle them the same as zext/trunc.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000834 case Instruction::ZExt:
Zhou Sheng771dbf72007-03-13 02:23:10 +0000835 case Instruction::Trunc: {
Chris Lattner0a2d74b2008-05-19 20:27:56 +0000836 // Note that we handle pointer operands here because of inttoptr/ptrtoint
837 // which fall through here.
Dan Gohmaneee962e2008-04-10 18:43:06 +0000838 const Type *SrcTy = I->getOperand(0)->getType();
839 uint32_t SrcBitWidth = TD ?
840 TD->getTypeSizeInBits(SrcTy) :
841 SrcTy->getPrimitiveSizeInBits();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000842 APInt MaskIn(Mask);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000843 MaskIn.zextOrTrunc(SrcBitWidth);
844 KnownZero.zextOrTrunc(SrcBitWidth);
845 KnownOne.zextOrTrunc(SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000846 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000847 KnownZero.zextOrTrunc(BitWidth);
848 KnownOne.zextOrTrunc(BitWidth);
849 // Any top bits are known to be zero.
850 if (BitWidth > SrcBitWidth)
851 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000852 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000853 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000854 case Instruction::BitCast: {
855 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohmaneee962e2008-04-10 18:43:06 +0000856 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000857 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
858 return;
859 }
860 break;
861 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000862 case Instruction::SExt: {
863 // Compute the bits in the result that are not present in the input.
864 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000865 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000866
Zhou Shengaa305ab2007-03-28 02:19:03 +0000867 APInt MaskIn(Mask);
868 MaskIn.trunc(SrcBitWidth);
869 KnownZero.trunc(SrcBitWidth);
870 KnownOne.trunc(SrcBitWidth);
871 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000872 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000873 KnownZero.zext(BitWidth);
874 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000875
876 // If the sign bit of the input is known set or clear, then we know the
877 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000878 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000879 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000880 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000881 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000882 return;
883 }
884 case Instruction::Shl:
885 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
886 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000887 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000888 APInt Mask2(Mask.lshr(ShiftAmt));
889 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000890 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000891 KnownZero <<= ShiftAmt;
892 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000893 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000894 return;
895 }
896 break;
897 case Instruction::LShr:
898 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
899 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000901 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000902
903 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000904 APInt Mask2(Mask.shl(ShiftAmt));
905 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000906 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
907 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000909 // high bits known zero.
910 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000911 return;
912 }
913 break;
914 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000915 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000916 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000918 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000919
920 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000921 APInt Mask2(Mask.shl(ShiftAmt));
922 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
926
Zhou Shengaa305ab2007-03-28 02:19:03 +0000927 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000929 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000930 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000931 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000932 return;
933 }
934 break;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000935 case Instruction::Sub: {
936 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937 // We know that the top bits of C-X are clear if X contains less bits
938 // than C (i.e. no wrap-around can happen). For example, 20-X is
939 // positive if we can prove that X is >= 0 and < 16.
940 if (!CLHS->getValue().isNegative()) {
941 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942 // NLZ can't be BitWidth with no sign bit
943 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohman23e8b712008-04-28 17:02:21 +0000944 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
945 Depth+1);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000946
Dan Gohman23e8b712008-04-28 17:02:21 +0000947 // If all of the MaskV bits are known to be zero, then we know the
948 // output top bits are zero, because we now know that the output is
949 // from [0-C].
950 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohmaneee962e2008-04-10 18:43:06 +0000951 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952 // Top bits known zero.
953 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohmaneee962e2008-04-10 18:43:06 +0000954 }
Dan Gohmaneee962e2008-04-10 18:43:06 +0000955 }
956 }
957 }
958 // fall through
Duncan Sands1d57a752008-03-21 08:32:17 +0000959 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000960 // Output known-0 bits are known if clear or set in both the low clear bits
961 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
962 // low 3 bits clear.
Dan Gohman23e8b712008-04-28 17:02:21 +0000963 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
966 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
967
968 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
970 KnownZeroOut = std::min(KnownZeroOut,
971 KnownZero2.countTrailingOnes());
972
973 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000974 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000975 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000976 case Instruction::SRem:
977 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978 APInt RA = Rem->getValue();
979 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +0000980 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000981 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
983
984 // The sign of a remainder is equal to the sign of the first
985 // operand (zero being positive).
986 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987 KnownZero2 |= ~LowBits;
988 else if (KnownOne2[BitWidth-1])
989 KnownOne2 |= ~LowBits;
990
991 KnownZero |= KnownZero2 & Mask;
992 KnownOne |= KnownOne2 & Mask;
993
994 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
995 }
996 }
997 break;
Dan Gohman23e8b712008-04-28 17:02:21 +0000998 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000999 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001001 if (RA.isPowerOf2()) {
1002 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001003 APInt Mask2 = LowBits & Mask;
1004 KnownZero |= ~LowBits & Mask;
1005 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001007 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001008 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001009 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001010
1011 // Since the result is less than or equal to either operand, any leading
1012 // zero bits in either operand must also exist in the result.
1013 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1015 Depth+1);
1016 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1017 Depth+1);
1018
1019 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020 KnownZero2.countLeadingOnes());
1021 KnownOne.clear();
1022 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001023 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001024 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00001025
1026 case Instruction::Alloca:
1027 case Instruction::Malloc: {
1028 AllocationInst *AI = cast<AllocationInst>(V);
1029 unsigned Align = AI->getAlignment();
1030 if (Align == 0 && TD) {
1031 if (isa<AllocaInst>(AI))
1032 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033 else if (isa<MallocInst>(AI)) {
1034 // Malloc returns maximally aligned memory.
1035 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1036 Align =
1037 std::max(Align,
1038 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1039 Align =
1040 std::max(Align,
1041 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1042 }
1043 }
1044
1045 if (Align > 0)
1046 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047 CountTrailingZeros_32(Align));
1048 break;
1049 }
1050 case Instruction::GetElementPtr: {
1051 // Analyze all of the subscripts of this getelementptr instruction
1052 // to determine if we can prove known low zero bits.
1053 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055 ComputeMaskedBits(I->getOperand(0), LocalMask,
1056 LocalKnownZero, LocalKnownOne, Depth+1);
1057 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1058
1059 gep_type_iterator GTI = gep_type_begin(I);
1060 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061 Value *Index = I->getOperand(i);
1062 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063 // Handle struct member offset arithmetic.
1064 if (!TD) return;
1065 const StructLayout *SL = TD->getStructLayout(STy);
1066 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067 uint64_t Offset = SL->getElementOffset(Idx);
1068 TrailZ = std::min(TrailZ,
1069 CountTrailingZeros_64(Offset));
1070 } else {
1071 // Handle array index arithmetic.
1072 const Type *IndexedTy = GTI.getIndexedType();
1073 if (!IndexedTy->isSized()) return;
1074 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078 ComputeMaskedBits(Index, LocalMask,
1079 LocalKnownZero, LocalKnownOne, Depth+1);
1080 TrailZ = std::min(TrailZ,
1081 CountTrailingZeros_64(TypeSize) +
1082 LocalKnownZero.countTrailingOnes());
1083 }
1084 }
1085
1086 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1087 break;
1088 }
1089 case Instruction::PHI: {
1090 PHINode *P = cast<PHINode>(I);
1091 // Handle the case of a simple two-predecessor recurrence PHI.
1092 // There's a lot more that could theoretically be done here, but
1093 // this is sufficient to catch some interesting cases.
1094 if (P->getNumIncomingValues() == 2) {
1095 for (unsigned i = 0; i != 2; ++i) {
1096 Value *L = P->getIncomingValue(i);
1097 Value *R = P->getIncomingValue(!i);
1098 User *LU = dyn_cast<User>(L);
1099 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1100 // Check for operations that have the property that if
1101 // both their operands have low zero bits, the result
1102 // will have low zero bits.
1103 if (Opcode == Instruction::Add ||
1104 Opcode == Instruction::Sub ||
1105 Opcode == Instruction::And ||
1106 Opcode == Instruction::Or ||
1107 Opcode == Instruction::Mul) {
1108 Value *LL = LU->getOperand(0);
1109 Value *LR = LU->getOperand(1);
1110 // Find a recurrence.
1111 if (LL == I)
1112 L = LR;
1113 else if (LR == I)
1114 L = LL;
1115 else
1116 break;
1117 // Ok, we have a PHI of the form L op= R. Check for low
1118 // zero bits.
1119 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1120 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1121 Mask2 = APInt::getLowBitsSet(BitWidth,
1122 KnownZero2.countTrailingOnes());
1123 KnownOne2.clear();
1124 KnownZero2.clear();
1125 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1126 KnownZero = Mask &
1127 APInt::getLowBitsSet(BitWidth,
1128 KnownZero2.countTrailingOnes());
1129 break;
1130 }
1131 }
1132 }
1133 break;
1134 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001135 case Instruction::Call:
1136 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1137 switch (II->getIntrinsicID()) {
1138 default: break;
1139 case Intrinsic::ctpop:
1140 case Intrinsic::ctlz:
1141 case Intrinsic::cttz: {
1142 unsigned LowBits = Log2_32(BitWidth)+1;
1143 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1144 break;
1145 }
1146 }
1147 }
1148 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +00001149 }
1150}
1151
Reid Spencere7816b52007-03-08 01:52:58 +00001152/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1153/// this predicate to simplify operations downstream. Mask is known to be zero
1154/// for bits that V cannot have.
Dan Gohmaneee962e2008-04-10 18:43:06 +00001155bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1156 unsigned Depth) {
Zhou Shengedd089c2007-03-12 16:54:56 +00001157 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +00001158 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1159 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1160 return (KnownZero & Mask) == Mask;
1161}
1162
Chris Lattner255d8912006-02-11 09:31:47 +00001163/// ShrinkDemandedConstant - Check to see if the specified operand of the
1164/// specified instruction is a constant integer. If so, check to see if there
1165/// are any bits set in the constant that are not demanded. If so, shrink the
1166/// constant and return true.
1167static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +00001168 APInt Demanded) {
1169 assert(I && "No instruction?");
1170 assert(OpNo < I->getNumOperands() && "Operand index too large");
1171
1172 // If the operand is not a constant integer, nothing to do.
1173 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1174 if (!OpC) return false;
1175
1176 // If there are no bits set that aren't demanded, nothing to do.
1177 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1178 if ((~Demanded & OpC->getValue()) == 0)
1179 return false;
1180
1181 // This instruction is producing bits that are not demanded. Shrink the RHS.
1182 Demanded &= OpC->getValue();
1183 I->setOperand(OpNo, ConstantInt::get(Demanded));
1184 return true;
1185}
1186
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001187// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1188// set of known zero and one bits, compute the maximum and minimum values that
1189// could have the specified known zero and known one bits, returning them in
1190// min/max.
1191static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +00001192 const APInt& KnownZero,
1193 const APInt& KnownOne,
1194 APInt& Min, APInt& Max) {
1195 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1196 assert(KnownZero.getBitWidth() == BitWidth &&
1197 KnownOne.getBitWidth() == BitWidth &&
1198 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1199 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001200 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001201
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001202 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1203 // bit if it is unknown.
1204 Min = KnownOne;
1205 Max = KnownOne|UnknownBits;
1206
Zhou Sheng4acf1552007-03-28 05:15:57 +00001207 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001208 Min.set(BitWidth-1);
1209 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001210 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001211}
1212
1213// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1214// a set of known zero and one bits, compute the maximum and minimum values that
1215// could have the specified known zero and known one bits, returning them in
1216// min/max.
1217static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001218 const APInt &KnownZero,
1219 const APInt &KnownOne,
1220 APInt &Min, APInt &Max) {
1221 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +00001222 assert(KnownZero.getBitWidth() == BitWidth &&
1223 KnownOne.getBitWidth() == BitWidth &&
1224 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1225 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001226 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001227
1228 // The minimum value is when the unknown bits are all zeros.
1229 Min = KnownOne;
1230 // The maximum value is when the unknown bits are all ones.
1231 Max = KnownOne|UnknownBits;
1232}
Chris Lattner255d8912006-02-11 09:31:47 +00001233
Reid Spencer8cb68342007-03-12 17:25:59 +00001234/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1235/// value based on the demanded bits. When this function is called, it is known
1236/// that only the bits set in DemandedMask of the result of V are ever used
1237/// downstream. Consequently, depending on the mask and V, it may be possible
1238/// to replace V with a constant or one of its operands. In such cases, this
1239/// function does the replacement and returns true. In all other cases, it
1240/// returns false after analyzing the expression and setting KnownOne and known
1241/// to be one in the expression. KnownZero contains all the bits that are known
1242/// to be zero in the expression. These are provided to potentially allow the
1243/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1244/// the expression. KnownOne and KnownZero always follow the invariant that
1245/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1246/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1247/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1248/// and KnownOne must all be the same.
1249bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1250 APInt& KnownZero, APInt& KnownOne,
1251 unsigned Depth) {
1252 assert(V != 0 && "Null pointer of Value???");
1253 assert(Depth <= 6 && "Limit Search Depth");
1254 uint32_t BitWidth = DemandedMask.getBitWidth();
1255 const IntegerType *VTy = cast<IntegerType>(V->getType());
1256 assert(VTy->getBitWidth() == BitWidth &&
1257 KnownZero.getBitWidth() == BitWidth &&
1258 KnownOne.getBitWidth() == BitWidth &&
1259 "Value *V, DemandedMask, KnownZero and KnownOne \
1260 must have same BitWidth");
1261 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1262 // We know all of the bits for a constant!
1263 KnownOne = CI->getValue() & DemandedMask;
1264 KnownZero = ~KnownOne & DemandedMask;
1265 return false;
1266 }
1267
Zhou Sheng96704452007-03-14 03:21:24 +00001268 KnownZero.clear();
1269 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 if (!V->hasOneUse()) { // Other users may use these bits.
1271 if (Depth != 0) { // Not at the root.
1272 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1273 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1274 return false;
1275 }
1276 // If this is the root being simplified, allow it to have multiple uses,
1277 // just set the DemandedMask to all bits.
1278 DemandedMask = APInt::getAllOnesValue(BitWidth);
1279 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1280 if (V != UndefValue::get(VTy))
1281 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1282 return false;
1283 } else if (Depth == 6) { // Limit search depth.
1284 return false;
1285 }
1286
1287 Instruction *I = dyn_cast<Instruction>(V);
1288 if (!I) return false; // Only analyze instructions.
1289
Reid Spencer8cb68342007-03-12 17:25:59 +00001290 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1291 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1292 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001293 default:
1294 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1295 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001296 case Instruction::And:
1297 // If either the LHS or the RHS are Zero, the result is zero.
1298 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1299 RHSKnownZero, RHSKnownOne, Depth+1))
1300 return true;
1301 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1302 "Bits known to be one AND zero?");
1303
1304 // If something is known zero on the RHS, the bits aren't demanded on the
1305 // LHS.
1306 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1307 LHSKnownZero, LHSKnownOne, Depth+1))
1308 return true;
1309 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1310 "Bits known to be one AND zero?");
1311
1312 // If all of the demanded bits are known 1 on one side, return the other.
1313 // These bits cannot contribute to the result of the 'and'.
1314 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1315 (DemandedMask & ~LHSKnownZero))
1316 return UpdateValueUsesWith(I, I->getOperand(0));
1317 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1318 (DemandedMask & ~RHSKnownZero))
1319 return UpdateValueUsesWith(I, I->getOperand(1));
1320
1321 // If all of the demanded bits in the inputs are known zeros, return zero.
1322 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1323 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1324
1325 // If the RHS is a constant, see if we can simplify it.
1326 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1327 return UpdateValueUsesWith(I, I);
1328
1329 // Output known-1 bits are only known if set in both the LHS & RHS.
1330 RHSKnownOne &= LHSKnownOne;
1331 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1332 RHSKnownZero |= LHSKnownZero;
1333 break;
1334 case Instruction::Or:
1335 // If either the LHS or the RHS are One, the result is One.
1336 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1337 RHSKnownZero, RHSKnownOne, Depth+1))
1338 return true;
1339 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1340 "Bits known to be one AND zero?");
1341 // If something is known one on the RHS, the bits aren't demanded on the
1342 // LHS.
1343 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1344 LHSKnownZero, LHSKnownOne, Depth+1))
1345 return true;
1346 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1347 "Bits known to be one AND zero?");
1348
1349 // If all of the demanded bits are known zero on one side, return the other.
1350 // These bits cannot contribute to the result of the 'or'.
1351 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1352 (DemandedMask & ~LHSKnownOne))
1353 return UpdateValueUsesWith(I, I->getOperand(0));
1354 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1355 (DemandedMask & ~RHSKnownOne))
1356 return UpdateValueUsesWith(I, I->getOperand(1));
1357
1358 // If all of the potentially set bits on one side are known to be set on
1359 // the other side, just use the 'other' side.
1360 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1361 (DemandedMask & (~RHSKnownZero)))
1362 return UpdateValueUsesWith(I, I->getOperand(0));
1363 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1364 (DemandedMask & (~LHSKnownZero)))
1365 return UpdateValueUsesWith(I, I->getOperand(1));
1366
1367 // If the RHS is a constant, see if we can simplify it.
1368 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1369 return UpdateValueUsesWith(I, I);
1370
1371 // Output known-0 bits are only known if clear in both the LHS & RHS.
1372 RHSKnownZero &= LHSKnownZero;
1373 // Output known-1 are known to be set if set in either the LHS | RHS.
1374 RHSKnownOne |= LHSKnownOne;
1375 break;
1376 case Instruction::Xor: {
1377 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1378 RHSKnownZero, RHSKnownOne, Depth+1))
1379 return true;
1380 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1381 "Bits known to be one AND zero?");
1382 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1383 LHSKnownZero, LHSKnownOne, Depth+1))
1384 return true;
1385 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1386 "Bits known to be one AND zero?");
1387
1388 // If all of the demanded bits are known zero on one side, return the other.
1389 // These bits cannot contribute to the result of the 'xor'.
1390 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1391 return UpdateValueUsesWith(I, I->getOperand(0));
1392 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1393 return UpdateValueUsesWith(I, I->getOperand(1));
1394
1395 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1396 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1397 (RHSKnownOne & LHSKnownOne);
1398 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1399 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1400 (RHSKnownOne & LHSKnownZero);
1401
1402 // If all of the demanded bits are known to be zero on one side or the
1403 // other, turn this into an *inclusive* or.
1404 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1405 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1406 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001407 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 I->getName());
1409 InsertNewInstBefore(Or, *I);
1410 return UpdateValueUsesWith(I, Or);
1411 }
1412
1413 // If all of the demanded bits on one side are known, and all of the set
1414 // bits on that side are also known to be set on the other side, turn this
1415 // into an AND, as we know the bits will be cleared.
1416 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1417 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1418 // all known
1419 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1420 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1421 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001422 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Reid Spencer8cb68342007-03-12 17:25:59 +00001423 InsertNewInstBefore(And, *I);
1424 return UpdateValueUsesWith(I, And);
1425 }
1426 }
1427
1428 // If the RHS is a constant, see if we can simplify it.
1429 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1430 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1431 return UpdateValueUsesWith(I, I);
1432
1433 RHSKnownZero = KnownZeroOut;
1434 RHSKnownOne = KnownOneOut;
1435 break;
1436 }
1437 case Instruction::Select:
1438 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1439 RHSKnownZero, RHSKnownOne, Depth+1))
1440 return true;
1441 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1442 LHSKnownZero, LHSKnownOne, Depth+1))
1443 return true;
1444 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1445 "Bits known to be one AND zero?");
1446 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1447 "Bits known to be one AND zero?");
1448
1449 // If the operands are constants, see if we can simplify them.
1450 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1451 return UpdateValueUsesWith(I, I);
1452 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1453 return UpdateValueUsesWith(I, I);
1454
1455 // Only known if known in both the LHS and RHS.
1456 RHSKnownOne &= LHSKnownOne;
1457 RHSKnownZero &= LHSKnownZero;
1458 break;
1459 case Instruction::Trunc: {
1460 uint32_t truncBf =
1461 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001462 DemandedMask.zext(truncBf);
1463 RHSKnownZero.zext(truncBf);
1464 RHSKnownOne.zext(truncBf);
1465 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1466 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001467 return true;
1468 DemandedMask.trunc(BitWidth);
1469 RHSKnownZero.trunc(BitWidth);
1470 RHSKnownOne.trunc(BitWidth);
1471 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1472 "Bits known to be one AND zero?");
1473 break;
1474 }
1475 case Instruction::BitCast:
1476 if (!I->getOperand(0)->getType()->isInteger())
1477 return false;
1478
1479 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1480 RHSKnownZero, RHSKnownOne, Depth+1))
1481 return true;
1482 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1483 "Bits known to be one AND zero?");
1484 break;
1485 case Instruction::ZExt: {
1486 // Compute the bits in the result that are not present in the input.
1487 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001488 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001489
Zhou Shengd48653a2007-03-29 04:45:55 +00001490 DemandedMask.trunc(SrcBitWidth);
1491 RHSKnownZero.trunc(SrcBitWidth);
1492 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001493 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1494 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001495 return true;
1496 DemandedMask.zext(BitWidth);
1497 RHSKnownZero.zext(BitWidth);
1498 RHSKnownOne.zext(BitWidth);
1499 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1500 "Bits known to be one AND zero?");
1501 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001502 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001503 break;
1504 }
1505 case Instruction::SExt: {
1506 // Compute the bits in the result that are not present in the input.
1507 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001508 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001509
Reid Spencer8cb68342007-03-12 17:25:59 +00001510 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001511 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001512
Zhou Sheng01542f32007-03-29 02:26:30 +00001513 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001514 // If any of the sign extended bits are demanded, we know that the sign
1515 // bit is demanded.
1516 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001517 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001518
Zhou Shengd48653a2007-03-29 04:45:55 +00001519 InputDemandedBits.trunc(SrcBitWidth);
1520 RHSKnownZero.trunc(SrcBitWidth);
1521 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001522 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1523 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001524 return true;
1525 InputDemandedBits.zext(BitWidth);
1526 RHSKnownZero.zext(BitWidth);
1527 RHSKnownOne.zext(BitWidth);
1528 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1529 "Bits known to be one AND zero?");
1530
1531 // If the sign bit of the input is known set or clear, then we know the
1532 // top bits of the result.
1533
1534 // If the input sign bit is known zero, or if the NewBits are not demanded
1535 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001536 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001537 {
1538 // Convert to ZExt cast
1539 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1540 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001541 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001542 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001543 }
1544 break;
1545 }
1546 case Instruction::Add: {
1547 // Figure out what the input bits are. If the top bits of the and result
1548 // are not demanded, then the add doesn't demand them from its input
1549 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001550 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001551
1552 // If there is a constant on the RHS, there are a variety of xformations
1553 // we can do.
1554 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1555 // If null, this should be simplified elsewhere. Some of the xforms here
1556 // won't work if the RHS is zero.
1557 if (RHS->isZero())
1558 break;
1559
1560 // If the top bit of the output is demanded, demand everything from the
1561 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001562 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001563
1564 // Find information about known zero/one bits in the input.
1565 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1566 LHSKnownZero, LHSKnownOne, Depth+1))
1567 return true;
1568
1569 // If the RHS of the add has bits set that can't affect the input, reduce
1570 // the constant.
1571 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1572 return UpdateValueUsesWith(I, I);
1573
1574 // Avoid excess work.
1575 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1576 break;
1577
1578 // Turn it into OR if input bits are zero.
1579 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1580 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001581 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001582 I->getName());
1583 InsertNewInstBefore(Or, *I);
1584 return UpdateValueUsesWith(I, Or);
1585 }
1586
1587 // We can say something about the output known-zero and known-one bits,
1588 // depending on potential carries from the input constant and the
1589 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1590 // bits set and the RHS constant is 0x01001, then we know we have a known
1591 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1592
1593 // To compute this, we first compute the potential carry bits. These are
1594 // the bits which may be modified. I'm not aware of a better way to do
1595 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001596 const APInt& RHSVal = RHS->getValue();
1597 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001598
1599 // Now that we know which bits have carries, compute the known-1/0 sets.
1600
1601 // Bits are known one if they are known zero in one operand and one in the
1602 // other, and there is no input carry.
1603 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1604 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1605
1606 // Bits are known zero if they are known zero in both operands and there
1607 // is no input carry.
1608 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1609 } else {
1610 // If the high-bits of this ADD are not demanded, then it does not demand
1611 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001612 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001613 // Right fill the mask of bits for this ADD to demand the most
1614 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001615 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001616 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1617 LHSKnownZero, LHSKnownOne, Depth+1))
1618 return true;
1619 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1620 LHSKnownZero, LHSKnownOne, Depth+1))
1621 return true;
1622 }
1623 }
1624 break;
1625 }
1626 case Instruction::Sub:
1627 // If the high-bits of this SUB are not demanded, then it does not demand
1628 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001629 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001630 // Right fill the mask of bits for this SUB to demand the most
1631 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001632 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001633 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001634 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1635 LHSKnownZero, LHSKnownOne, Depth+1))
1636 return true;
1637 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1638 LHSKnownZero, LHSKnownOne, Depth+1))
1639 return true;
1640 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001641 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1642 // the known zeros and ones.
1643 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001644 break;
1645 case Instruction::Shl:
1646 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001647 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001648 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1649 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001650 RHSKnownZero, RHSKnownOne, Depth+1))
1651 return true;
1652 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1653 "Bits known to be one AND zero?");
1654 RHSKnownZero <<= ShiftAmt;
1655 RHSKnownOne <<= ShiftAmt;
1656 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001657 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001658 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001659 }
1660 break;
1661 case Instruction::LShr:
1662 // For a logical shift right
1663 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001664 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001665
Reid Spencer8cb68342007-03-12 17:25:59 +00001666 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001667 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1668 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001669 RHSKnownZero, RHSKnownOne, Depth+1))
1670 return true;
1671 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1672 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001673 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1674 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001675 if (ShiftAmt) {
1676 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001677 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001678 RHSKnownZero |= HighBits; // high bits known zero.
1679 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001680 }
1681 break;
1682 case Instruction::AShr:
1683 // If this is an arithmetic shift right and only the low-bit is set, we can
1684 // always convert this into a logical shr, even if the shift amount is
1685 // variable. The low bit of the shift cannot be an input sign bit unless
1686 // the shift amount is >= the size of the datatype, which is undefined.
1687 if (DemandedMask == 1) {
1688 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001689 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001690 I->getOperand(0), I->getOperand(1), I->getName());
1691 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1692 return UpdateValueUsesWith(I, NewVal);
1693 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001694
1695 // If the sign bit is the only bit demanded by this ashr, then there is no
1696 // need to do it, the shift doesn't change the high bit.
1697 if (DemandedMask.isSignBit())
1698 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001699
1700 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001701 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001702
Reid Spencer8cb68342007-03-12 17:25:59 +00001703 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001704 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001705 // If any of the "high bits" are demanded, we should set the sign bit as
1706 // demanded.
1707 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1708 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001709 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001710 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001711 RHSKnownZero, RHSKnownOne, Depth+1))
1712 return true;
1713 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1714 "Bits known to be one AND zero?");
1715 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001716 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001717 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1718 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1719
1720 // Handle the sign bits.
1721 APInt SignBit(APInt::getSignBit(BitWidth));
1722 // Adjust to where it is now in the mask.
1723 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1724
1725 // If the input sign bit is known to be zero, or if none of the top bits
1726 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001727 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001728 (HighBits & ~DemandedMask) == HighBits) {
1729 // Perform the logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001730 Value *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001731 I->getOperand(0), SA, I->getName());
1732 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1733 return UpdateValueUsesWith(I, NewVal);
1734 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1735 RHSKnownOne |= HighBits;
1736 }
1737 }
1738 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001739 case Instruction::SRem:
1740 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1741 APInt RA = Rem->getValue();
1742 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman23e1df82008-05-06 00:51:48 +00001743 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001744 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1745 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1746 LHSKnownZero, LHSKnownOne, Depth+1))
1747 return true;
1748
1749 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1750 LHSKnownZero |= ~LowBits;
1751 else if (LHSKnownOne[BitWidth-1])
1752 LHSKnownOne |= ~LowBits;
1753
1754 KnownZero |= LHSKnownZero & DemandedMask;
1755 KnownOne |= LHSKnownOne & DemandedMask;
1756
1757 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1758 }
1759 }
1760 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001761 case Instruction::URem: {
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001762 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1763 APInt RA = Rem->getValue();
Dan Gohman23e1df82008-05-06 00:51:48 +00001764 if (RA.isPowerOf2()) {
1765 APInt LowBits = (RA - 1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001766 APInt Mask2 = LowBits & DemandedMask;
1767 KnownZero |= ~LowBits & DemandedMask;
1768 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1769 KnownZero, KnownOne, Depth+1))
1770 return true;
1771
1772 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohman23e8b712008-04-28 17:02:21 +00001773 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001774 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001775 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001776
1777 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1778 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohmane85b7582008-05-01 19:13:24 +00001779 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1780 KnownZero2, KnownOne2, Depth+1))
1781 return true;
1782
Dan Gohman23e8b712008-04-28 17:02:21 +00001783 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohmane85b7582008-05-01 19:13:24 +00001784 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohman23e8b712008-04-28 17:02:21 +00001785 KnownZero2, KnownOne2, Depth+1))
1786 return true;
1787
1788 Leaders = std::max(Leaders,
1789 KnownZero2.countLeadingOnes());
1790 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001791 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001792 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001793 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001794
1795 // If the client is only demanding bits that we know, return the known
1796 // constant.
1797 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1798 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1799 return false;
1800}
1801
Chris Lattner867b99f2006-10-05 06:55:50 +00001802
1803/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1804/// 64 or fewer elements. DemandedElts contains the set of elements that are
1805/// actually used by the caller. This method analyzes which elements of the
1806/// operand are undef and returns that information in UndefElts.
1807///
1808/// If the information about demanded elements can be used to simplify the
1809/// operation, the operation is simplified, then the resultant value is
1810/// returned. This returns null if no change was made.
1811Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1812 uint64_t &UndefElts,
1813 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001814 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001815 assert(VWidth <= 64 && "Vector too wide to analyze!");
1816 uint64_t EltMask = ~0ULL >> (64-VWidth);
1817 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1818 "Invalid DemandedElts!");
1819
1820 if (isa<UndefValue>(V)) {
1821 // If the entire vector is undefined, just return this info.
1822 UndefElts = EltMask;
1823 return 0;
1824 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1825 UndefElts = EltMask;
1826 return UndefValue::get(V->getType());
1827 }
1828
1829 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001830 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1831 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001832 Constant *Undef = UndefValue::get(EltTy);
1833
1834 std::vector<Constant*> Elts;
1835 for (unsigned i = 0; i != VWidth; ++i)
1836 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1837 Elts.push_back(Undef);
1838 UndefElts |= (1ULL << i);
1839 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1840 Elts.push_back(Undef);
1841 UndefElts |= (1ULL << i);
1842 } else { // Otherwise, defined.
1843 Elts.push_back(CP->getOperand(i));
1844 }
1845
1846 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001847 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001848 return NewCP != CP ? NewCP : 0;
1849 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001850 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001851 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001852 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001853 Constant *Zero = Constant::getNullValue(EltTy);
1854 Constant *Undef = UndefValue::get(EltTy);
1855 std::vector<Constant*> Elts;
1856 for (unsigned i = 0; i != VWidth; ++i)
1857 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1858 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001859 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001860 }
1861
1862 if (!V->hasOneUse()) { // Other users may use these bits.
1863 if (Depth != 0) { // Not at the root.
1864 // TODO: Just compute the UndefElts information recursively.
1865 return false;
1866 }
1867 return false;
1868 } else if (Depth == 10) { // Limit search depth.
1869 return false;
1870 }
1871
1872 Instruction *I = dyn_cast<Instruction>(V);
1873 if (!I) return false; // Only analyze instructions.
1874
1875 bool MadeChange = false;
1876 uint64_t UndefElts2;
1877 Value *TmpV;
1878 switch (I->getOpcode()) {
1879 default: break;
1880
1881 case Instruction::InsertElement: {
1882 // If this is a variable index, we don't know which element it overwrites.
1883 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001884 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001885 if (Idx == 0) {
1886 // Note that we can't propagate undef elt info, because we don't know
1887 // which elt is getting updated.
1888 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1889 UndefElts2, Depth+1);
1890 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1891 break;
1892 }
1893
1894 // If this is inserting an element that isn't demanded, remove this
1895 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001896 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001897 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1898 return AddSoonDeadInstToWorklist(*I, 0);
1899
1900 // Otherwise, the element inserted overwrites whatever was there, so the
1901 // input demanded set is simpler than the output set.
1902 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1903 DemandedElts & ~(1ULL << IdxNo),
1904 UndefElts, Depth+1);
1905 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1906
1907 // The inserted element is defined.
1908 UndefElts |= 1ULL << IdxNo;
1909 break;
1910 }
Chris Lattner69878332007-04-14 22:29:23 +00001911 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001912 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001913 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1914 if (!VTy) break;
1915 unsigned InVWidth = VTy->getNumElements();
1916 uint64_t InputDemandedElts = 0;
1917 unsigned Ratio;
1918
1919 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001920 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001921 // elements as are demanded of us.
1922 Ratio = 1;
1923 InputDemandedElts = DemandedElts;
1924 } else if (VWidth > InVWidth) {
1925 // Untested so far.
1926 break;
1927
1928 // If there are more elements in the result than there are in the source,
1929 // then an input element is live if any of the corresponding output
1930 // elements are live.
1931 Ratio = VWidth/InVWidth;
1932 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1933 if (DemandedElts & (1ULL << OutIdx))
1934 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1935 }
1936 } else {
1937 // Untested so far.
1938 break;
1939
1940 // If there are more elements in the source than there are in the result,
1941 // then an input element is live if the corresponding output element is
1942 // live.
1943 Ratio = InVWidth/VWidth;
1944 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1945 if (DemandedElts & (1ULL << InIdx/Ratio))
1946 InputDemandedElts |= 1ULL << InIdx;
1947 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001948
Chris Lattner69878332007-04-14 22:29:23 +00001949 // div/rem demand all inputs, because they don't want divide by zero.
1950 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1951 UndefElts2, Depth+1);
1952 if (TmpV) {
1953 I->setOperand(0, TmpV);
1954 MadeChange = true;
1955 }
1956
1957 UndefElts = UndefElts2;
1958 if (VWidth > InVWidth) {
1959 assert(0 && "Unimp");
1960 // If there are more elements in the result than there are in the source,
1961 // then an output element is undef if the corresponding input element is
1962 // undef.
1963 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1964 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1965 UndefElts |= 1ULL << OutIdx;
1966 } else if (VWidth < InVWidth) {
1967 assert(0 && "Unimp");
1968 // If there are more elements in the source than there are in the result,
1969 // then a result element is undef if all of the corresponding input
1970 // elements are undef.
1971 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1972 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1973 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1974 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1975 }
1976 break;
1977 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001978 case Instruction::And:
1979 case Instruction::Or:
1980 case Instruction::Xor:
1981 case Instruction::Add:
1982 case Instruction::Sub:
1983 case Instruction::Mul:
1984 // div/rem demand all inputs, because they don't want divide by zero.
1985 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1986 UndefElts, Depth+1);
1987 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1988 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1989 UndefElts2, Depth+1);
1990 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1991
1992 // Output elements are undefined if both are undefined. Consider things
1993 // like undef&0. The result is known zero, not undef.
1994 UndefElts &= UndefElts2;
1995 break;
1996
1997 case Instruction::Call: {
1998 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1999 if (!II) break;
2000 switch (II->getIntrinsicID()) {
2001 default: break;
2002
2003 // Binary vector operations that work column-wise. A dest element is a
2004 // function of the corresponding input elements from the two inputs.
2005 case Intrinsic::x86_sse_sub_ss:
2006 case Intrinsic::x86_sse_mul_ss:
2007 case Intrinsic::x86_sse_min_ss:
2008 case Intrinsic::x86_sse_max_ss:
2009 case Intrinsic::x86_sse2_sub_sd:
2010 case Intrinsic::x86_sse2_mul_sd:
2011 case Intrinsic::x86_sse2_min_sd:
2012 case Intrinsic::x86_sse2_max_sd:
2013 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2014 UndefElts, Depth+1);
2015 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2016 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2017 UndefElts2, Depth+1);
2018 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2019
2020 // If only the low elt is demanded and this is a scalarizable intrinsic,
2021 // scalarize it now.
2022 if (DemandedElts == 1) {
2023 switch (II->getIntrinsicID()) {
2024 default: break;
2025 case Intrinsic::x86_sse_sub_ss:
2026 case Intrinsic::x86_sse_mul_ss:
2027 case Intrinsic::x86_sse2_sub_sd:
2028 case Intrinsic::x86_sse2_mul_sd:
2029 // TODO: Lower MIN/MAX/ABS/etc
2030 Value *LHS = II->getOperand(1);
2031 Value *RHS = II->getOperand(2);
2032 // Extract the element as scalars.
2033 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2034 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2035
2036 switch (II->getIntrinsicID()) {
2037 default: assert(0 && "Case stmts out of sync!");
2038 case Intrinsic::x86_sse_sub_ss:
2039 case Intrinsic::x86_sse2_sub_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002040 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002041 II->getName()), *II);
2042 break;
2043 case Intrinsic::x86_sse_mul_ss:
2044 case Intrinsic::x86_sse2_mul_sd:
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002045 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00002046 II->getName()), *II);
2047 break;
2048 }
2049
2050 Instruction *New =
Gabor Greif051a9502008-04-06 20:25:17 +00002051 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2052 II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00002053 InsertNewInstBefore(New, *II);
2054 AddSoonDeadInstToWorklist(*II, 0);
2055 return New;
2056 }
2057 }
2058
2059 // Output elements are undefined if both are undefined. Consider things
2060 // like undef&0. The result is known zero, not undef.
2061 UndefElts &= UndefElts2;
2062 break;
2063 }
2064 break;
2065 }
2066 }
2067 return MadeChange ? I : 0;
2068}
2069
Dan Gohman45b4e482008-05-19 22:14:15 +00002070/// ComputeNumSignBits - Return the number of times the sign bit of the
2071/// register is replicated into the other bits. We know that at least 1 bit
2072/// is always equal to the sign bit (itself), but other cases can give us
2073/// information. For example, immediately after an "ashr X, 2", we know that
2074/// the top 3 bits are all equal to each other, so we return 3.
2075///
2076unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2077 const IntegerType *Ty = cast<IntegerType>(V->getType());
2078 unsigned TyBits = Ty->getBitWidth();
2079 unsigned Tmp, Tmp2;
Dan Gohmana332f172008-05-23 02:28:01 +00002080 unsigned FirstAnswer = 1;
Dan Gohman45b4e482008-05-19 22:14:15 +00002081
2082 if (Depth == 6)
2083 return 1; // Limit search depth.
2084
2085 User *U = dyn_cast<User>(V);
2086 switch (getOpcode(V)) {
2087 default: break;
2088 case Instruction::SExt:
2089 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2090 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2091
2092 case Instruction::AShr:
2093 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
Dan Gohmanf35c8822008-05-20 21:01:12 +00002094 // ashr X, C -> adds C sign bits.
Dan Gohman45b4e482008-05-19 22:14:15 +00002095 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2096 Tmp += C->getZExtValue();
2097 if (Tmp > TyBits) Tmp = TyBits;
2098 }
2099 return Tmp;
2100 case Instruction::Shl:
2101 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2102 // shl destroys sign bits.
2103 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2104 if (C->getZExtValue() >= TyBits || // Bad shift.
2105 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2106 return Tmp - C->getZExtValue();
2107 }
2108 break;
2109 case Instruction::And:
2110 case Instruction::Or:
Dan Gohmana332f172008-05-23 02:28:01 +00002111 case Instruction::Xor: // NOT is handled here.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002112 // Logical binary ops preserve the number of sign bits at the worst.
2113 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2114 if (Tmp != 1) {
2115 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohmana332f172008-05-23 02:28:01 +00002116 FirstAnswer = std::min(Tmp, Tmp2);
2117 // We computed what we know about the sign bits as our first
2118 // answer. Now proceed to the generic code that uses
2119 // ComputeMaskedBits, and pick whichever answer is better.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002120 }
Dan Gohmana332f172008-05-23 02:28:01 +00002121 break;
Dan Gohman45b4e482008-05-19 22:14:15 +00002122
2123 case Instruction::Select:
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002124 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002125 if (Tmp == 1) return 1; // Early out.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002126 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
Dan Gohman45b4e482008-05-19 22:14:15 +00002127 return std::min(Tmp, Tmp2);
2128
2129 case Instruction::Add:
2130 // Add can have at most one carry bit. Thus we know that the output
2131 // is, at worst, one more bit than the inputs.
2132 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2133 if (Tmp == 1) return 1; // Early out.
2134
2135 // Special case decrementing a value (ADD X, -1):
2136 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2137 if (CRHS->isAllOnesValue()) {
2138 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2139 APInt Mask = APInt::getAllOnesValue(TyBits);
2140 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2141
2142 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2143 // sign bits set.
2144 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2145 return TyBits;
2146
2147 // If we are subtracting one from a positive number, there is no carry
2148 // out of the result.
2149 if (KnownZero.isNegative())
2150 return Tmp;
2151 }
2152
2153 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2154 if (Tmp2 == 1) return 1;
2155 return std::min(Tmp, Tmp2)-1;
2156 break;
2157
2158 case Instruction::Sub:
2159 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2160 if (Tmp2 == 1) return 1;
2161
2162 // Handle NEG.
2163 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2164 if (CLHS->isNullValue()) {
2165 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2166 APInt Mask = APInt::getAllOnesValue(TyBits);
2167 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2168 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2169 // sign bits set.
2170 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2171 return TyBits;
2172
2173 // If the input is known to be positive (the sign bit is known clear),
2174 // the output of the NEG has the same number of sign bits as the input.
2175 if (KnownZero.isNegative())
2176 return Tmp2;
2177
2178 // Otherwise, we treat this like a SUB.
2179 }
2180
2181 // Sub can have at most one carry bit. Thus we know that the output
2182 // is, at worst, one more bit than the inputs.
2183 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2184 if (Tmp == 1) return 1; // Early out.
2185 return std::min(Tmp, Tmp2)-1;
2186 break;
2187 case Instruction::Trunc:
2188 // FIXME: it's tricky to do anything useful for this, but it is an important
2189 // case for targets like X86.
2190 break;
2191 }
2192
2193 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2194 // use this information.
2195 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2196 APInt Mask = APInt::getAllOnesValue(TyBits);
2197 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2198
2199 if (KnownZero.isNegative()) { // sign bit is 0
2200 Mask = KnownZero;
2201 } else if (KnownOne.isNegative()) { // sign bit is 1;
2202 Mask = KnownOne;
2203 } else {
2204 // Nothing known.
Dan Gohmana332f172008-05-23 02:28:01 +00002205 return FirstAnswer;
Dan Gohman45b4e482008-05-19 22:14:15 +00002206 }
2207
2208 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2209 // the number of identical bits in the top of the input value.
2210 Mask = ~Mask;
2211 Mask <<= Mask.getBitWidth()-TyBits;
2212 // Return # leading zeros. We use 'min' here in case Val was zero before
2213 // shifting. We don't want to return '64' as for an i32 "0".
Dan Gohmana332f172008-05-23 02:28:01 +00002214 return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
Dan Gohman45b4e482008-05-19 22:14:15 +00002215}
2216
2217
Chris Lattner564a7272003-08-13 19:01:45 +00002218/// AssociativeOpt - Perform an optimization on an associative operator. This
2219/// function is designed to check a chain of associative operators for a
2220/// potential to apply a certain optimization. Since the optimization may be
2221/// applicable if the expression was reassociated, this checks the chain, then
2222/// reassociates the expression as necessary to expose the optimization
2223/// opportunity. This makes use of a special Functor, which must define
2224/// 'shouldApply' and 'apply' methods.
2225///
2226template<typename Functor>
Dan Gohman76d402b2008-05-20 01:14:05 +00002227static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00002228 unsigned Opcode = Root.getOpcode();
2229 Value *LHS = Root.getOperand(0);
2230
2231 // Quick check, see if the immediate LHS matches...
2232 if (F.shouldApply(LHS))
2233 return F.apply(Root);
2234
2235 // Otherwise, if the LHS is not of the same opcode as the root, return.
2236 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00002237 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00002238 // Should we apply this transform to the RHS?
2239 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2240
2241 // If not to the RHS, check to see if we should apply to the LHS...
2242 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2243 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2244 ShouldApply = true;
2245 }
2246
2247 // If the functor wants to apply the optimization to the RHS of LHSI,
2248 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2249 if (ShouldApply) {
2250 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00002251
Chris Lattner564a7272003-08-13 19:01:45 +00002252 // Now all of the instructions are in the current basic block, go ahead
2253 // and perform the reassociation.
2254 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2255
2256 // First move the selected RHS to the LHS of the root...
2257 Root.setOperand(0, LHSI->getOperand(1));
2258
2259 // Make what used to be the LHS of the root be the user of the root...
2260 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00002261 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00002262 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2263 return 0;
2264 }
Chris Lattner65725312004-04-16 18:08:07 +00002265 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00002266 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00002267 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2268 BasicBlock::iterator ARI = &Root; ++ARI;
2269 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2270 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00002271
2272 // Now propagate the ExtraOperand down the chain of instructions until we
2273 // get to LHSI.
2274 while (TmpLHSI != LHSI) {
2275 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00002276 // Move the instruction to immediately before the chain we are
2277 // constructing to avoid breaking dominance properties.
2278 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2279 BB->getInstList().insert(ARI, NextLHSI);
2280 ARI = NextLHSI;
2281
Chris Lattner564a7272003-08-13 19:01:45 +00002282 Value *NextOp = NextLHSI->getOperand(1);
2283 NextLHSI->setOperand(1, ExtraOperand);
2284 TmpLHSI = NextLHSI;
2285 ExtraOperand = NextOp;
2286 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002287
Chris Lattner564a7272003-08-13 19:01:45 +00002288 // Now that the instructions are reassociated, have the functor perform
2289 // the transformation...
2290 return F.apply(Root);
2291 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002292
Chris Lattner564a7272003-08-13 19:01:45 +00002293 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2294 }
2295 return 0;
2296}
2297
Dan Gohman844731a2008-05-13 00:00:25 +00002298namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002299
Nick Lewycky02d639f2008-05-23 04:34:58 +00002300// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002301struct AddRHS {
2302 Value *RHS;
2303 AddRHS(Value *rhs) : RHS(rhs) {}
2304 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2305 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002306 return BinaryOperator::CreateShl(Add.getOperand(0),
2307 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002308 }
2309};
2310
2311// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2312// iff C1&C2 == 0
2313struct AddMaskingAnd {
2314 Constant *C2;
2315 AddMaskingAnd(Constant *c) : C2(c) {}
2316 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002317 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002318 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002319 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002320 }
2321 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002322 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002323 }
2324};
2325
Dan Gohman844731a2008-05-13 00:00:25 +00002326}
2327
Chris Lattner6e7ba452005-01-01 16:22:27 +00002328static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002329 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002330 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002331 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00002332 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00002333
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002334 return IC->InsertNewInstBefore(CastInst::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00002335 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002336 }
2337
Chris Lattner2eefe512004-04-09 19:05:30 +00002338 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002339 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2340 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002341
Chris Lattner2eefe512004-04-09 19:05:30 +00002342 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2343 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00002344 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2345 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002346 }
2347
2348 Value *Op0 = SO, *Op1 = ConstOperand;
2349 if (!ConstIsRHS)
2350 std::swap(Op0, Op1);
2351 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002352 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002353 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00002354 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002355 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002356 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00002357 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00002358 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00002359 abort();
2360 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00002361 return IC->InsertNewInstBefore(New, I);
2362}
2363
2364// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2365// constant as the other operand, try to fold the binary operator into the
2366// select arguments. This also works for Cast instructions, which obviously do
2367// not have a second operand.
2368static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2369 InstCombiner *IC) {
2370 // Don't modify shared select instructions
2371 if (!SI->hasOneUse()) return 0;
2372 Value *TV = SI->getOperand(1);
2373 Value *FV = SI->getOperand(2);
2374
2375 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002376 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002377 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002378
Chris Lattner6e7ba452005-01-01 16:22:27 +00002379 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2380 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2381
Gabor Greif051a9502008-04-06 20:25:17 +00002382 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2383 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002384 }
2385 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002386}
2387
Chris Lattner4e998b22004-09-29 05:07:12 +00002388
2389/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2390/// node as operand #0, see if we can fold the instruction into the PHI (which
2391/// is only possible if all operands to the PHI are constants).
2392Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2393 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002394 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002395 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002396
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002397 // Check to see if all of the operands of the PHI are constants. If there is
2398 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002399 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002400 BasicBlock *NonConstBB = 0;
2401 for (unsigned i = 0; i != NumPHIValues; ++i)
2402 if (!isa<Constant>(PN->getIncomingValue(i))) {
2403 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002404 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002405 NonConstBB = PN->getIncomingBlock(i);
2406
2407 // If the incoming non-constant value is in I's block, we have an infinite
2408 // loop.
2409 if (NonConstBB == I.getParent())
2410 return 0;
2411 }
2412
2413 // If there is exactly one non-constant value, we can insert a copy of the
2414 // operation in that block. However, if this is a critical edge, we would be
2415 // inserting the computation one some other paths (e.g. inside a loop). Only
2416 // do this if the pred block is unconditionally branching into the phi block.
2417 if (NonConstBB) {
2418 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2419 if (!BI || !BI->isUnconditional()) return 0;
2420 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002421
2422 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002423 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002424 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002425 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002426 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002427
2428 // Next, add all of the operands to the PHI.
2429 if (I.getNumOperands() == 2) {
2430 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002431 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002432 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002433 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002434 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2435 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2436 else
2437 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002438 } else {
2439 assert(PN->getIncomingBlock(i) == NonConstBB);
2440 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002441 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002442 PN->getIncomingValue(i), C, "phitmp",
2443 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002444 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002445 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002446 CI->getPredicate(),
2447 PN->getIncomingValue(i), C, "phitmp",
2448 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002449 else
2450 assert(0 && "Unknown binop!");
2451
Chris Lattnerdbab3862007-03-02 21:28:56 +00002452 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002453 }
2454 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002455 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002456 } else {
2457 CastInst *CI = cast<CastInst>(&I);
2458 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002459 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002460 Value *InV;
2461 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002462 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002463 } else {
2464 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002465 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002466 I.getType(), "phitmp",
2467 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002468 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002469 }
2470 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002471 }
2472 }
2473 return ReplaceInstUsesWith(I, NewPN);
2474}
2475
Chris Lattner2454a2e2008-01-29 06:52:45 +00002476
2477/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2478/// value is never equal to -0.0.
2479///
2480/// Note that this function will need to be revisited when we support nondefault
2481/// rounding modes!
2482///
2483static bool CannotBeNegativeZero(const Value *V) {
2484 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2485 return !CFP->getValueAPF().isNegZero();
2486
Chris Lattner2454a2e2008-01-29 06:52:45 +00002487 if (const Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002488 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
Chris Lattner2454a2e2008-01-29 06:52:45 +00002489 if (I->getOpcode() == Instruction::Add &&
2490 isa<ConstantFP>(I->getOperand(1)) &&
2491 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2492 return true;
2493
Chris Lattner0a2d74b2008-05-19 20:27:56 +00002494 // sitofp and uitofp turn into +0.0 for zero.
2495 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2496 return true;
2497
Chris Lattner2454a2e2008-01-29 06:52:45 +00002498 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2499 if (II->getIntrinsicID() == Intrinsic::sqrt)
2500 return CannotBeNegativeZero(II->getOperand(1));
2501
2502 if (const CallInst *CI = dyn_cast<CallInst>(I))
2503 if (const Function *F = CI->getCalledFunction()) {
2504 if (F->isDeclaration()) {
2505 switch (F->getNameLen()) {
2506 case 3: // abs(x) != -0.0
2507 if (!strcmp(F->getNameStart(), "abs")) return true;
2508 break;
2509 case 4: // abs[lf](x) != -0.0
2510 if (!strcmp(F->getNameStart(), "absf")) return true;
2511 if (!strcmp(F->getNameStart(), "absl")) return true;
2512 break;
2513 }
2514 }
2515 }
2516 }
2517
2518 return false;
2519}
2520
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002521/// WillNotOverflowSignedAdd - Return true if we can prove that:
2522/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2523/// This basically requires proving that the add in the original type would not
2524/// overflow to change the sign bit or have a carry out.
2525bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2526 // There are different heuristics we can use for this. Here are some simple
2527 // ones.
2528
2529 // Add has the property that adding any two 2's complement numbers can only
2530 // have one carry bit which can change a sign. As such, if LHS and RHS each
2531 // have at least two sign bits, we know that the addition of the two values will
2532 // sign extend fine.
2533 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2534 return true;
2535
2536
2537 // If one of the operands only has one non-zero bit, and if the other operand
2538 // has a known-zero bit in a more significant place than it (not including the
2539 // sign bit) the ripple may go up to and fill the zero, but won't change the
2540 // sign. For example, (X & ~4) + 1.
2541
2542 // TODO: Implement.
2543
2544 return false;
2545}
2546
Chris Lattner2454a2e2008-01-29 06:52:45 +00002547
Chris Lattner7e708292002-06-25 16:13:24 +00002548Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002549 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002550 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002551
Chris Lattner66331a42004-04-10 22:01:55 +00002552 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002553 // X + undef -> undef
2554 if (isa<UndefValue>(RHS))
2555 return ReplaceInstUsesWith(I, RHS);
2556
Chris Lattner66331a42004-04-10 22:01:55 +00002557 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002558 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002559 if (RHSC->isNullValue())
2560 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002561 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002562 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2563 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002564 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002565 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002566
Chris Lattner66331a42004-04-10 22:01:55 +00002567 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002568 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002569 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002570 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002571 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002572 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002573
2574 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2575 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002576 if (!isa<VectorType>(I.getType())) {
2577 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2578 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2579 KnownZero, KnownOne))
2580 return &I;
2581 }
Chris Lattner66331a42004-04-10 22:01:55 +00002582 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002583
2584 if (isa<PHINode>(LHS))
2585 if (Instruction *NV = FoldOpIntoPhi(I))
2586 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002587
Chris Lattner4f637d42006-01-06 17:59:59 +00002588 ConstantInt *XorRHS = 0;
2589 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002590 if (isa<ConstantInt>(RHSC) &&
2591 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002592 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002593 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002594
Zhou Sheng4351c642007-04-02 08:20:41 +00002595 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002596 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2597 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002598 do {
2599 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002600 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2601 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002602 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2603 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002604 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002605 if (!MaskedValueIsZero(XorLHS,
2606 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002607 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002608 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002609 }
2610 }
2611 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002612 C0080Val = APIntOps::lshr(C0080Val, Size);
2613 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2614 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002615
Reid Spencer35c38852007-03-28 01:36:16 +00002616 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002617 // with funny bit widths then this switch statement should be removed. It
2618 // is just here to get the size of the "middle" type back up to something
2619 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002620 const Type *MiddleType = 0;
2621 switch (Size) {
2622 default: break;
2623 case 32: MiddleType = Type::Int32Ty; break;
2624 case 16: MiddleType = Type::Int16Ty; break;
2625 case 8: MiddleType = Type::Int8Ty; break;
2626 }
2627 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002628 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002629 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002630 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002631 }
2632 }
Chris Lattner66331a42004-04-10 22:01:55 +00002633 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002634
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002635 // X + X --> X << 1
Nick Lewycky02d639f2008-05-23 04:34:58 +00002636 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002637 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002638
2639 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2640 if (RHSI->getOpcode() == Instruction::Sub)
2641 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2642 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2643 }
2644 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2645 if (LHSI->getOpcode() == Instruction::Sub)
2646 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2647 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2648 }
Robert Bocchino71698282004-07-27 21:02:21 +00002649 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002650
Chris Lattner5c4afb92002-05-08 22:46:53 +00002651 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002652 // -A + -B --> -(A + B)
2653 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002654 if (LHS->getType()->isIntOrIntVector()) {
2655 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002656 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattnere10c0b92008-02-18 17:50:16 +00002657 InsertNewInstBefore(NewAdd, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002658 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002659 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002660 }
2661
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002662 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002663 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002664
2665 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002666 if (!isa<Constant>(RHS))
2667 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002669
Misha Brukmanfd939082005-04-21 23:48:37 +00002670
Chris Lattner50af16a2004-11-13 19:50:12 +00002671 ConstantInt *C2;
2672 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2673 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002674 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002675
2676 // X*C1 + X*C2 --> X * (C1+C2)
2677 ConstantInt *C1;
2678 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002679 return BinaryOperator::CreateMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002680 }
2681
2682 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002683 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002684 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002685
Chris Lattnere617c9e2007-01-05 02:17:46 +00002686 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002687 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2688 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002689
Chris Lattnerad3448c2003-02-18 19:57:07 +00002690
Chris Lattner564a7272003-08-13 19:01:45 +00002691 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002692 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002693 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2694 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002695
2696 // A+B --> A|B iff A and B have no bits set in common.
2697 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2698 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2699 APInt LHSKnownOne(IT->getBitWidth(), 0);
2700 APInt LHSKnownZero(IT->getBitWidth(), 0);
2701 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2702 if (LHSKnownZero != 0) {
2703 APInt RHSKnownOne(IT->getBitWidth(), 0);
2704 APInt RHSKnownZero(IT->getBitWidth(), 0);
2705 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2706
2707 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002708 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002709 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002710 }
2711 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002712
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002713 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002714 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002715 Value *W, *X, *Y, *Z;
2716 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2717 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2718 if (W != Y) {
2719 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002720 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002721 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002722 std::swap(W, X);
2723 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002724 std::swap(Y, Z);
2725 std::swap(W, X);
2726 }
2727 }
2728
2729 if (W == Y) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002730 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002731 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002732 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002733 }
2734 }
2735 }
2736
Chris Lattner6b032052003-10-02 15:11:26 +00002737 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002738 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002739 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002740 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002741
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002742 // (X & FF00) + xx00 -> (X+xx00) & FF00
2743 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002744 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002745 if (Anded == CRHS) {
2746 // See if all bits from the first bit set in the Add RHS up are included
2747 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002748 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002749
2750 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002751 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002752
2753 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002754 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002755
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002756 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2757 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002758 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002759 LHS->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002760 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002761 }
2762 }
2763 }
2764
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002765 // Try to fold constant add into select arguments.
2766 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002767 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002768 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002769 }
2770
Reid Spencer1628cec2006-10-26 06:15:43 +00002771 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002772 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002773 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002774 CastInst *CI = dyn_cast<CastInst>(LHS);
2775 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002776 if (!CI) {
2777 CI = dyn_cast<CastInst>(RHS);
2778 Other = LHS;
2779 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002780 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002781 (CI->getType()->getPrimitiveSizeInBits() ==
2782 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002783 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002784 unsigned AS =
2785 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002786 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2787 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greif051a9502008-04-06 20:25:17 +00002788 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002789 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002790 }
2791 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002792
Chris Lattner42790482007-12-20 01:56:58 +00002793 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002794 {
2795 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2796 Value *Other = RHS;
2797 if (!SI) {
2798 SI = dyn_cast<SelectInst>(RHS);
2799 Other = LHS;
2800 }
Chris Lattner42790482007-12-20 01:56:58 +00002801 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002802 Value *TV = SI->getTrueValue();
2803 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002804 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002805
2806 // Can we fold the add into the argument of the select?
2807 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002808 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2809 A == Other) // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002810 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner42790482007-12-20 01:56:58 +00002811 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2812 A == Other) // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002813 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002814 }
2815 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002816
2817 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2818 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2819 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2820 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002821
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002822 // Check for (add (sext x), y), see if we can merge this into an
2823 // integer add followed by a sext.
2824 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2825 // (add (sext x), cst) --> (sext (add x, cst'))
2826 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2827 Constant *CI =
2828 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2829 if (LHSConv->hasOneUse() &&
2830 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2831 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2832 // Insert the new, smaller add.
2833 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2834 CI, "addconv");
2835 InsertNewInstBefore(NewAdd, I);
2836 return new SExtInst(NewAdd, I.getType());
2837 }
2838 }
2839
2840 // (add (sext x), (sext y)) --> (sext (add int x, y))
2841 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2842 // Only do this if x/y have the same type, if at last one of them has a
2843 // single use (so we don't increase the number of sexts), and if the
2844 // integer add will not overflow.
2845 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2846 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2847 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2848 RHSConv->getOperand(0))) {
2849 // Insert the new integer add.
2850 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2851 RHSConv->getOperand(0),
2852 "addconv");
2853 InsertNewInstBefore(NewAdd, I);
2854 return new SExtInst(NewAdd, I.getType());
2855 }
2856 }
2857 }
2858
2859 // Check for (add double (sitofp x), y), see if we can merge this into an
2860 // integer add followed by a promotion.
2861 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2862 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2863 // ... if the constant fits in the integer value. This is useful for things
2864 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2865 // requires a constant pool load, and generally allows the add to be better
2866 // instcombined.
2867 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2868 Constant *CI =
2869 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2870 if (LHSConv->hasOneUse() &&
2871 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2872 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2873 // Insert the new integer add.
2874 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2875 CI, "addconv");
2876 InsertNewInstBefore(NewAdd, I);
2877 return new SIToFPInst(NewAdd, I.getType());
2878 }
2879 }
2880
2881 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2882 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2883 // Only do this if x/y have the same type, if at last one of them has a
2884 // single use (so we don't increase the number of int->fp conversions),
2885 // and if the integer add will not overflow.
2886 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2887 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2888 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2889 RHSConv->getOperand(0))) {
2890 // Insert the new integer add.
2891 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2892 RHSConv->getOperand(0),
2893 "addconv");
2894 InsertNewInstBefore(NewAdd, I);
2895 return new SIToFPInst(NewAdd, I.getType());
2896 }
2897 }
2898 }
2899
Chris Lattner7e708292002-06-25 16:13:24 +00002900 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002901}
2902
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002903// isSignBit - Return true if the value represented by the constant only has the
2904// highest order bit set.
2905static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002906 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002907 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002908}
2909
Chris Lattner7e708292002-06-25 16:13:24 +00002910Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002911 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002912
Chris Lattner233f7dc2002-08-12 21:17:25 +00002913 if (Op0 == Op1) // sub X, X -> 0
2914 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002915
Chris Lattner233f7dc2002-08-12 21:17:25 +00002916 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002917 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002918 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002919
Chris Lattnere87597f2004-10-16 18:11:37 +00002920 if (isa<UndefValue>(Op0))
2921 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2922 if (isa<UndefValue>(Op1))
2923 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2924
Chris Lattnerd65460f2003-11-05 01:06:05 +00002925 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2926 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002927 if (C->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002928 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002929
Chris Lattnerd65460f2003-11-05 01:06:05 +00002930 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002931 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002932 if (match(Op1, m_Not(m_Value(X))))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002933 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002934
Chris Lattner76b7a062007-01-15 07:02:54 +00002935 // -(X >>u 31) -> (X >>s 31)
2936 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002937 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002938 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002939 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002940 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002941 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002942 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002943 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002944 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002945 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002946 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002947 }
2948 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002949 }
2950 else if (SI->getOpcode() == Instruction::AShr) {
2951 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2952 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002953 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002954 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002955 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002956 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002957 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002958 }
2959 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002960 }
2961 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002962 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002963
2964 // Try to fold constant sub into select arguments.
2965 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002966 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002967 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002968
2969 if (isa<PHINode>(Op0))
2970 if (Instruction *NV = FoldOpIntoPhi(I))
2971 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002972 }
2973
Chris Lattner43d84d62005-04-07 16:15:25 +00002974 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2975 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002976 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002977 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002978 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002979 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002980 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002981 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2982 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2983 // C1-(X+C2) --> (C1-C2)-X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002984 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002985 Op1I->getOperand(0));
2986 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002987 }
2988
Chris Lattnerfd059242003-10-15 16:48:29 +00002989 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002990 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2991 // is not used by anyone else...
2992 //
Chris Lattner0517e722004-02-02 20:09:56 +00002993 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002994 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002995 // Swap the two operands of the subexpr...
2996 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2997 Op1I->setOperand(0, IIOp1);
2998 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002999
Chris Lattnera2881962003-02-18 19:28:33 +00003000 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003001 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003002 }
3003
3004 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3005 //
3006 if (Op1I->getOpcode() == Instruction::And &&
3007 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3008 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3009
Chris Lattnerf523d062004-06-09 05:08:07 +00003010 Value *NewNot =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003011 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3012 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00003013 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00003014
Reid Spencerac5209e2006-10-16 23:08:08 +00003015 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00003016 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00003017 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00003018 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00003019 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003020 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00003021 ConstantExpr::getNeg(DivRHS));
3022
Chris Lattnerad3448c2003-02-18 19:57:07 +00003023 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00003024 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00003025 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003026 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003027 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00003028 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00003029
3030 // X - ((X / Y) * Y) --> X % Y
3031 if (Op1I->getOpcode() == Instruction::Mul)
3032 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3033 if (Op0 == I->getOperand(0) &&
3034 Op1I->getOperand(1) == I->getOperand(1)) {
3035 if (I->getOpcode() == Instruction::SDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003036 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003037 if (I->getOpcode() == Instruction::UDiv)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003038 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohman5d066ff2007-09-17 17:31:57 +00003039 }
Chris Lattner40371712002-05-09 01:29:19 +00003040 }
Chris Lattner43d84d62005-04-07 16:15:25 +00003041 }
Chris Lattnera2881962003-02-18 19:28:33 +00003042
Chris Lattner9919e3d2006-12-02 00:13:08 +00003043 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003044 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00003045 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003046 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3047 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3048 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3049 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00003050 } else if (Op0I->getOpcode() == Instruction::Sub) {
3051 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003052 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00003053 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003054 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003055
Chris Lattner50af16a2004-11-13 19:50:12 +00003056 ConstantInt *C1;
3057 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00003058 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003059 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00003060
Chris Lattner50af16a2004-11-13 19:50:12 +00003061 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3062 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003063 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00003064 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003065 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003066}
3067
Chris Lattnera0141b92007-07-15 20:42:37 +00003068/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3069/// comparison only checks the sign bit. If it only checks the sign bit, set
3070/// TrueIfSigned if the result of the comparison is true when the input value is
3071/// signed.
3072static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3073 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003074 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003075 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3076 TrueIfSigned = true;
3077 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003078 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3079 TrueIfSigned = true;
3080 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003081 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3082 TrueIfSigned = false;
3083 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003084 case ICmpInst::ICMP_UGT:
3085 // True if LHS u> RHS and RHS == high-bit-mask - 1
3086 TrueIfSigned = true;
3087 return RHS->getValue() ==
3088 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3089 case ICmpInst::ICMP_UGE:
3090 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3091 TrueIfSigned = true;
3092 return RHS->getValue() ==
3093 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00003094 default:
3095 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003096 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003097}
3098
Chris Lattner7e708292002-06-25 16:13:24 +00003099Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003100 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00003101 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003102
Chris Lattnere87597f2004-10-16 18:11:37 +00003103 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3104 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3105
Chris Lattner233f7dc2002-08-12 21:17:25 +00003106 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00003107 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3108 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003109
3110 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003111 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003112 if (SI->getOpcode() == Instruction::Shl)
3113 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003114 return BinaryOperator::CreateMul(SI->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003115 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003116
Zhou Sheng843f07672007-04-19 05:39:12 +00003117 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00003118 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3119 if (CI->equalsInt(1)) // X * 1 == X
3120 return ReplaceInstUsesWith(I, Op0);
3121 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003122 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003123
Zhou Sheng97b52c22007-03-29 01:57:21 +00003124 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003125 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003126 return BinaryOperator::CreateShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00003127 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003128 }
Robert Bocchino71698282004-07-27 21:02:21 +00003129 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00003130 if (Op1F->isNullValue())
3131 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00003132
Chris Lattnera2881962003-02-18 19:28:33 +00003133 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3134 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00003135 // We need a better interface for long double here.
3136 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3137 if (Op1F->isExactlyValue(1.0))
3138 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00003139 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003140
3141 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3142 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00003143 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003144 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003145 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003146 Op1, "tmp");
3147 InsertNewInstBefore(Add, I);
3148 Value *C1C2 = ConstantExpr::getMul(Op1,
3149 cast<Constant>(Op0I->getOperand(1)));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003150 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003151
3152 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003153
3154 // Try to fold constant mul into select arguments.
3155 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003156 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003157 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003158
3159 if (isa<PHINode>(Op0))
3160 if (Instruction *NV = FoldOpIntoPhi(I))
3161 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003162 }
3163
Chris Lattnera4f445b2003-03-10 23:23:04 +00003164 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3165 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003166 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003167
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003168 // If one of the operands of the multiply is a cast from a boolean value, then
3169 // we know the bool is either zero or one, so this is a 'masking' multiply.
3170 // See if we can simplify things based on how the boolean was originally
3171 // formed.
3172 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00003173 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003174 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003175 BoolCast = CI;
3176 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00003177 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00003178 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003179 BoolCast = CI;
3180 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003181 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003182 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3183 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00003184 bool TIS = false;
3185
Reid Spencere4d87aa2006-12-23 06:05:41 +00003186 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00003187 // multiply into a shift/and combination.
3188 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00003189 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3190 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003191 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00003192 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00003193 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00003194 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00003195 InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003196 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00003197 BoolCast->getOperand(0)->getName()+
3198 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003199
3200 // If the multiply type is not the same as the source type, sign extend
3201 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00003202 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00003203 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3204 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00003205 Instruction::CastOps opcode =
3206 (SrcBits == DstBits ? Instruction::BitCast :
3207 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3208 V = InsertCastBefore(opcode, V, I.getType(), I);
3209 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003210
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003211 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003212 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003213 }
3214 }
3215 }
3216
Chris Lattner7e708292002-06-25 16:13:24 +00003217 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003218}
3219
Reid Spencer1628cec2006-10-26 06:15:43 +00003220/// This function implements the transforms on div instructions that work
3221/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3222/// used by the visitors to those instructions.
3223/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003224Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003226
Chris Lattner50b2ca42008-02-19 06:12:18 +00003227 // undef / X -> 0 for integer.
3228 // undef / X -> undef for FP (the undef could be a snan).
3229 if (isa<UndefValue>(Op0)) {
3230 if (Op0->getType()->isFPOrFPVector())
3231 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003233 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003234
3235 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003236 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003237 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003238
Chris Lattner25feae52008-01-28 00:58:18 +00003239 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3240 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00003241 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00003242 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3243 // the same basic block, then we replace the select with Y, and the
3244 // condition of the select with false (if the cond value is in the same BB).
3245 // If the select has uses other than the div, this allows them to be
3246 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3247 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003248 if (ST->isNullValue()) {
3249 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3250 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003251 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00003252 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3253 I.setOperand(1, SI->getOperand(2));
3254 else
3255 UpdateValueUsesWith(SI, SI->getOperand(2));
3256 return &I;
3257 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003258
Chris Lattner25feae52008-01-28 00:58:18 +00003259 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3260 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00003261 if (ST->isNullValue()) {
3262 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3263 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003264 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00003265 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3266 I.setOperand(1, SI->getOperand(1));
3267 else
3268 UpdateValueUsesWith(SI, SI->getOperand(1));
3269 return &I;
3270 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003271 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003272
Reid Spencer1628cec2006-10-26 06:15:43 +00003273 return 0;
3274}
Misha Brukmanfd939082005-04-21 23:48:37 +00003275
Reid Spencer1628cec2006-10-26 06:15:43 +00003276/// This function implements the transforms common to both integer division
3277/// instructions (udiv and sdiv). It is called by the visitors to those integer
3278/// division instructions.
3279/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003280Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3282
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003283 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003284 if (Op0 == Op1) {
3285 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3286 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3287 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3288 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3289 }
3290
3291 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3292 return ReplaceInstUsesWith(I, CI);
3293 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003294
Reid Spencer1628cec2006-10-26 06:15:43 +00003295 if (Instruction *Common = commonDivTransforms(I))
3296 return Common;
3297
3298 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3299 // div X, 1 == X
3300 if (RHS->equalsInt(1))
3301 return ReplaceInstUsesWith(I, Op0);
3302
3303 // (X / C1) / C2 -> X / (C1*C2)
3304 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3305 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3306 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003307 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3308 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3309 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003310 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003311 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003312 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003313
Reid Spencerbca0e382007-03-23 20:05:17 +00003314 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003315 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3316 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3317 return R;
3318 if (isa<PHINode>(Op0))
3319 if (Instruction *NV = FoldOpIntoPhi(I))
3320 return NV;
3321 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003322 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003323
Chris Lattnera2881962003-02-18 19:28:33 +00003324 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003325 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003326 if (LHS->equalsInt(0))
3327 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3328
Reid Spencer1628cec2006-10-26 06:15:43 +00003329 return 0;
3330}
3331
3332Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3333 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3334
3335 // Handle the integer div common cases
3336 if (Instruction *Common = commonIDivTransforms(I))
3337 return Common;
3338
3339 // X udiv C^2 -> X >> C
3340 // Check to see if this is an unsigned division with an exact power of 2,
3341 // if so, convert to a right shift.
3342 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00003343 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003344 return BinaryOperator::CreateLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00003345 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003346 }
3347
3348 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003349 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003350 if (RHSI->getOpcode() == Instruction::Shl &&
3351 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003352 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003353 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003354 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003355 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00003356 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003357 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003358 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003359 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003360 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003361 }
3362 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003363 }
3364
Reid Spencer1628cec2006-10-26 06:15:43 +00003365 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3366 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003367 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003368 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003369 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003370 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003371 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003372 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003373 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003374 // Construct the "on true" case of the select
3375 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003376 Instruction *TSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003377 Op0, TC, SI->getName()+".t");
3378 TSI = InsertNewInstBefore(TSI, I);
3379
3380 // Construct the "on false" case of the select
3381 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003382 Instruction *FSI = BinaryOperator::CreateLShr(
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003383 Op0, FC, SI->getName()+".f");
3384 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00003385
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003386 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003387 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003388 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003389 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003390 return 0;
3391}
3392
Reid Spencer1628cec2006-10-26 06:15:43 +00003393Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3394 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3395
3396 // Handle the integer div common cases
3397 if (Instruction *Common = commonIDivTransforms(I))
3398 return Common;
3399
3400 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3401 // sdiv X, -1 == -X
3402 if (RHS->isAllOnesValue())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003403 return BinaryOperator::CreateNeg(Op0);
Reid Spencer1628cec2006-10-26 06:15:43 +00003404
3405 // -X/C -> X/-C
3406 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003407 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003408 }
3409
3410 // If the sign bits of both operands are zero (i.e. we can prove they are
3411 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003412 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003413 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00003414 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00003415 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003416 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003417 }
3418 }
3419
3420 return 0;
3421}
3422
3423Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3424 return commonDivTransforms(I);
3425}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003426
Reid Spencer0a783f72006-11-02 01:53:59 +00003427/// This function implements the transforms on rem instructions that work
3428/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3429/// is used by the visitors to those instructions.
3430/// @brief Transforms common to all three rem instructions
3431Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003432 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003433
Chris Lattner50b2ca42008-02-19 06:12:18 +00003434 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003435 if (Constant *LHS = dyn_cast<Constant>(Op0))
3436 if (LHS->isNullValue())
3437 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3438
Chris Lattner50b2ca42008-02-19 06:12:18 +00003439 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3440 if (I.getType()->isFPOrFPVector())
3441 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003442 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003443 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003444 if (isa<UndefValue>(Op1))
3445 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003446
3447 // Handle cases involving: rem X, (select Cond, Y, Z)
3448 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3449 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3450 // the same basic block, then we replace the select with Y, and the
3451 // condition of the select with false (if the cond value is in the same
3452 // BB). If the select has uses other than the div, this allows them to be
3453 // simplified also.
3454 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3455 if (ST->isNullValue()) {
3456 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3457 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003458 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00003459 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3460 I.setOperand(1, SI->getOperand(2));
3461 else
3462 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00003463 return &I;
3464 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003465 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3466 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3467 if (ST->isNullValue()) {
3468 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3469 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003470 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00003471 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3472 I.setOperand(1, SI->getOperand(1));
3473 else
3474 UpdateValueUsesWith(SI, SI->getOperand(1));
3475 return &I;
3476 }
Chris Lattner11a49f22005-11-05 07:28:37 +00003477 }
Chris Lattner5b73c082004-07-06 07:01:22 +00003478
Reid Spencer0a783f72006-11-02 01:53:59 +00003479 return 0;
3480}
3481
3482/// This function implements the transforms common to both integer remainder
3483/// instructions (urem and srem). It is called by the visitors to those integer
3484/// remainder instructions.
3485/// @brief Common integer remainder transforms
3486Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3487 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3488
3489 if (Instruction *common = commonRemTransforms(I))
3490 return common;
3491
Chris Lattner857e8cd2004-12-12 21:48:58 +00003492 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003493 // X % 0 == undef, we don't need to preserve faults!
3494 if (RHS->equalsInt(0))
3495 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3496
Chris Lattnera2881962003-02-18 19:28:33 +00003497 if (RHS->equalsInt(1)) // X % 1 == 0
3498 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3499
Chris Lattner97943922006-02-28 05:49:21 +00003500 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3501 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3502 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3503 return R;
3504 } else if (isa<PHINode>(Op0I)) {
3505 if (Instruction *NV = FoldOpIntoPhi(I))
3506 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003507 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003508
3509 // See if we can fold away this rem instruction.
3510 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3511 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3512 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3513 KnownZero, KnownOne))
3514 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003515 }
Chris Lattnera2881962003-02-18 19:28:33 +00003516 }
3517
Reid Spencer0a783f72006-11-02 01:53:59 +00003518 return 0;
3519}
3520
3521Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3522 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3523
3524 if (Instruction *common = commonIRemTransforms(I))
3525 return common;
3526
3527 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3528 // X urem C^2 -> X and C
3529 // Check to see if this is an unsigned remainder with an exact power of 2,
3530 // if so, convert to a bitwise and.
3531 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003532 if (C->getValue().isPowerOf2())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003533 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003534 }
3535
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003536 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003537 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3538 if (RHSI->getOpcode() == Instruction::Shl &&
3539 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003540 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003541 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003542 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003543 "tmp"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003544 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003545 }
3546 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003547 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003548
Reid Spencer0a783f72006-11-02 01:53:59 +00003549 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3550 // where C1&C2 are powers of two.
3551 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3552 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3553 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3554 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003555 if ((STO->getValue().isPowerOf2()) &&
3556 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003557 Value *TrueAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003558 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Reid Spencer0a783f72006-11-02 01:53:59 +00003559 Value *FalseAnd = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greif051a9502008-04-06 20:25:17 +00003561 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003562 }
3563 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003564 }
3565
Chris Lattner3f5b8772002-05-06 16:14:14 +00003566 return 0;
3567}
3568
Reid Spencer0a783f72006-11-02 01:53:59 +00003569Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3570 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3571
Dan Gohmancff55092007-11-05 23:16:33 +00003572 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003573 if (Instruction *common = commonIRemTransforms(I))
3574 return common;
3575
3576 if (Value *RHSNeg = dyn_castNegVal(Op1))
3577 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003578 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003579 // X % -Y -> X % Y
3580 AddUsesToWorkList(I);
3581 I.setOperand(1, RHSNeg);
3582 return &I;
3583 }
3584
Dan Gohmancff55092007-11-05 23:16:33 +00003585 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003586 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003587 if (I.getType()->isInteger()) {
3588 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3589 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3590 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003591 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003592 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003593 }
3594
3595 return 0;
3596}
3597
3598Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003599 return commonRemTransforms(I);
3600}
3601
Chris Lattner8b170942002-08-09 23:47:40 +00003602// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003603static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003604 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003605 if (!isSigned)
3606 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3607 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003608}
3609
3610// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003611static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003612 if (!isSigned)
3613 return C->getValue() == 1; // unsigned
3614
3615 // Calculate 1111111111000000000000
3616 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3617 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003618}
3619
Chris Lattner457dd822004-06-09 07:59:58 +00003620// isOneBitSet - Return true if there is exactly one bit set in the specified
3621// constant.
3622static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003623 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003624}
3625
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003626// isHighOnes - Return true if the constant is of the form 1+0+.
3627// This is the same as lowones(~X).
3628static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003629 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003630}
3631
Reid Spencere4d87aa2006-12-23 06:05:41 +00003632/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003633/// are carefully arranged to allow folding of expressions such as:
3634///
3635/// (A < B) | (A > B) --> (A != B)
3636///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637/// Note that this is only valid if the first and second predicates have the
3638/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003639///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003640/// Three bits are used to represent the condition, as follows:
3641/// 0 A > B
3642/// 1 A == B
3643/// 2 A < B
3644///
3645/// <=> Value Definition
3646/// 000 0 Always false
3647/// 001 1 A > B
3648/// 010 2 A == B
3649/// 011 3 A >= B
3650/// 100 4 A < B
3651/// 101 5 A != B
3652/// 110 6 A <= B
3653/// 111 7 Always true
3654///
3655static unsigned getICmpCode(const ICmpInst *ICI) {
3656 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003657 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 case ICmpInst::ICMP_UGT: return 1; // 001
3659 case ICmpInst::ICMP_SGT: return 1; // 001
3660 case ICmpInst::ICMP_EQ: return 2; // 010
3661 case ICmpInst::ICMP_UGE: return 3; // 011
3662 case ICmpInst::ICMP_SGE: return 3; // 011
3663 case ICmpInst::ICMP_ULT: return 4; // 100
3664 case ICmpInst::ICMP_SLT: return 4; // 100
3665 case ICmpInst::ICMP_NE: return 5; // 101
3666 case ICmpInst::ICMP_ULE: return 6; // 110
3667 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003668 // True -> 7
3669 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003670 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003671 return 0;
3672 }
3673}
3674
Reid Spencere4d87aa2006-12-23 06:05:41 +00003675/// getICmpValue - This is the complement of getICmpCode, which turns an
3676/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003677/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678/// of predicate to use in new icmp instructions.
3679static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3680 switch (code) {
3681 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003682 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003683 case 1:
3684 if (sign)
3685 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3686 else
3687 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3688 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3689 case 3:
3690 if (sign)
3691 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3692 else
3693 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3694 case 4:
3695 if (sign)
3696 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3697 else
3698 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3699 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3700 case 6:
3701 if (sign)
3702 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3703 else
3704 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003705 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003706 }
3707}
3708
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3710 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3711 (ICmpInst::isSignedPredicate(p1) &&
3712 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3713 (ICmpInst::isSignedPredicate(p2) &&
3714 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3715}
3716
3717namespace {
3718// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3719struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003720 InstCombiner &IC;
3721 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003722 ICmpInst::Predicate pred;
3723 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3724 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3725 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003726 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003727 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3728 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003729 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3730 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003731 return false;
3732 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003733 Instruction *apply(Instruction &Log) const {
3734 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3735 if (ICI->getOperand(0) != LHS) {
3736 assert(ICI->getOperand(1) == LHS);
3737 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003738 }
3739
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003740 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003741 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003742 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003743 unsigned Code;
3744 switch (Log.getOpcode()) {
3745 case Instruction::And: Code = LHSCode & RHSCode; break;
3746 case Instruction::Or: Code = LHSCode | RHSCode; break;
3747 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003748 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003749 }
3750
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003751 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3752 ICmpInst::isSignedPredicate(ICI->getPredicate());
3753
3754 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003755 if (Instruction *I = dyn_cast<Instruction>(RV))
3756 return I;
3757 // Otherwise, it's a constant boolean value...
3758 return IC.ReplaceInstUsesWith(Log, RV);
3759 }
3760};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003761} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003762
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003763// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3764// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003765// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003766Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003767 ConstantInt *OpRHS,
3768 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003769 BinaryOperator &TheAnd) {
3770 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003771 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003772 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003773 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003774
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003775 switch (Op->getOpcode()) {
3776 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003777 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003778 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003779 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003780 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003781 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003782 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003783 }
3784 break;
3785 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003786 if (Together == AndRHS) // (X | C) & C --> C
3787 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003788
Chris Lattner6e7ba452005-01-01 16:22:27 +00003789 if (Op->hasOneUse() && Together != OpRHS) {
3790 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003791 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003792 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003793 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003794 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003795 }
3796 break;
3797 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003798 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003799 // Adding a one to a single bit bit-field should be turned into an XOR
3800 // of the bit. First thing to check is to see if this AND is with a
3801 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003802 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003803
3804 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003805 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003806 // Ok, at this point, we know that we are masking the result of the
3807 // ADD down to exactly one bit. If the constant we are adding has
3808 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003809 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003810
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003811 // Check to see if any bits below the one bit set in AndRHSV are set.
3812 if ((AddRHS & (AndRHSV-1)) == 0) {
3813 // If not, the only thing that can effect the output of the AND is
3814 // the bit specified by AndRHSV. If that bit is set, the effect of
3815 // the XOR is to toggle the bit. If it is clear, then the ADD has
3816 // no effect.
3817 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3818 TheAnd.setOperand(0, X);
3819 return &TheAnd;
3820 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003821 // Pull the XOR out of the AND.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003822 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003823 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003824 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003825 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003826 }
3827 }
3828 }
3829 }
3830 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003831
3832 case Instruction::Shl: {
3833 // We know that the AND will not produce any of the bits shifted in, so if
3834 // the anded constant includes them, clear them now!
3835 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003836 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003837 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003838 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3839 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003840
Zhou Sheng290bec52007-03-29 08:15:12 +00003841 if (CI->getValue() == ShlMask) {
3842 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003843 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3844 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003845 TheAnd.setOperand(1, CI);
3846 return &TheAnd;
3847 }
3848 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003849 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003850 case Instruction::LShr:
3851 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003852 // We know that the AND will not produce any of the bits shifted in, so if
3853 // the anded constant includes them, clear them now! This only applies to
3854 // unsigned shifts, because a signed shr may bring in set bits!
3855 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003856 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003857 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003858 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3859 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003860
Zhou Sheng290bec52007-03-29 08:15:12 +00003861 if (CI->getValue() == ShrMask) {
3862 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003863 return ReplaceInstUsesWith(TheAnd, Op);
3864 } else if (CI != AndRHS) {
3865 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3866 return &TheAnd;
3867 }
3868 break;
3869 }
3870 case Instruction::AShr:
3871 // Signed shr.
3872 // See if this is shifting in some sign extension, then masking it out
3873 // with an and.
3874 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003875 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003876 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003877 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3878 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003879 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003880 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003881 // Make the argument unsigned.
3882 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003883 ShVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003884 BinaryOperator::CreateLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003885 Op->getName()), TheAnd);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003886 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003887 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003888 }
3889 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003890 }
3891 return 0;
3892}
3893
Chris Lattner8b170942002-08-09 23:47:40 +00003894
Chris Lattnera96879a2004-09-29 17:40:11 +00003895/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3896/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003897/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3898/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003899/// insert new instructions.
3900Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003901 bool isSigned, bool Inside,
3902 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003903 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003904 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003905 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003906
Chris Lattnera96879a2004-09-29 17:40:11 +00003907 if (Inside) {
3908 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003909 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003910
Reid Spencere4d87aa2006-12-23 06:05:41 +00003911 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003912 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003913 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003914 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3915 return new ICmpInst(pred, V, Hi);
3916 }
3917
3918 // Emit V-Lo <u Hi-Lo
3919 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003920 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003921 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003922 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3923 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003924 }
3925
3926 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003927 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003928
Reid Spencere4e40032007-03-21 23:19:50 +00003929 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003930 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003931 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003932 ICmpInst::Predicate pred = (isSigned ?
3933 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3934 return new ICmpInst(pred, V, Hi);
3935 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003936
Reid Spencere4e40032007-03-21 23:19:50 +00003937 // Emit V-Lo >u Hi-1-Lo
3938 // Note that Hi has already had one subtracted from it, above.
3939 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003940 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003941 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003942 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3943 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003944}
3945
Chris Lattner7203e152005-09-18 07:22:02 +00003946// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3947// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3948// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3949// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003950static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003951 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003952 uint32_t BitWidth = Val->getType()->getBitWidth();
3953 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003954
3955 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003956 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003957 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003958 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003959 return true;
3960}
3961
Chris Lattner7203e152005-09-18 07:22:02 +00003962/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3963/// where isSub determines whether the operator is a sub. If we can fold one of
3964/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003965///
3966/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3967/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3968/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3969///
3970/// return (A +/- B).
3971///
3972Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003973 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003974 Instruction &I) {
3975 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3976 if (!LHSI || LHSI->getNumOperands() != 2 ||
3977 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3978
3979 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3980
3981 switch (LHSI->getOpcode()) {
3982 default: return 0;
3983 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003984 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003985 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003986 if ((Mask->getValue().countLeadingZeros() +
3987 Mask->getValue().countPopulation()) ==
3988 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003989 break;
3990
3991 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3992 // part, we don't need any explicit masks to take them out of A. If that
3993 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003994 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003995 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003996 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003997 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003998 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003999 break;
4000 }
4001 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004002 return 0;
4003 case Instruction::Or:
4004 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004005 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004006 if ((Mask->getValue().countLeadingZeros() +
4007 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00004008 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004009 break;
4010 return 0;
4011 }
4012
4013 Instruction *New;
4014 if (isSub)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004015 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004016 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004017 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004018 return InsertNewInstBefore(New, I);
4019}
4020
Chris Lattner7e708292002-06-25 16:13:24 +00004021Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004022 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004023 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004024
Chris Lattnere87597f2004-10-16 18:11:37 +00004025 if (isa<UndefValue>(Op1)) // X & undef -> 0
4026 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4027
Chris Lattner6e7ba452005-01-01 16:22:27 +00004028 // and X, X = X
4029 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004030 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004031
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004032 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004033 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00004034 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00004035 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4036 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4037 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00004038 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00004039 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00004040 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004041 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004042 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004043 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004044 } else if (isa<ConstantAggregateZero>(Op1)) {
4045 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004046 }
4047 }
Chris Lattner9ca96412006-02-08 03:25:32 +00004048
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004049 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004050 const APInt& AndRHSMask = AndRHS->getValue();
4051 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004052
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004053 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004054 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004055 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004056 Value *Op0LHS = Op0I->getOperand(0);
4057 Value *Op0RHS = Op0I->getOperand(1);
4058 switch (Op0I->getOpcode()) {
4059 case Instruction::Xor:
4060 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004061 // If the mask is only needed on one incoming arm, push it up.
4062 if (Op0I->hasOneUse()) {
4063 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4064 // Not masking anything out for the LHS, move to RHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004065 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004066 Op0RHS->getName()+".masked");
4067 InsertNewInstBefore(NewRHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004068 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004069 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004070 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004071 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004072 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4073 // Not masking anything out for the RHS, move to LHS.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004074 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Chris Lattnerad1e3022005-01-23 20:26:55 +00004075 Op0LHS->getName()+".masked");
4076 InsertNewInstBefore(NewLHS, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004077 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004078 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4079 }
4080 }
4081
Chris Lattner6e7ba452005-01-01 16:22:27 +00004082 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004083 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004084 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4085 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004088 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004089 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004090 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004091 break;
4092
4093 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004094 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4095 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004098 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00004099 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004100 }
4101
Chris Lattner58403262003-07-23 19:25:52 +00004102 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004103 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004104 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004105 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004106 // If this is an integer truncation or change from signed-to-unsigned, and
4107 // if the source is an and/or with immediate, transform it. This
4108 // frequently occurs for bitfield accesses.
4109 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004110 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004111 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004112 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004113 if (CastOp->getOpcode() == Instruction::And) {
4114 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004115 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4116 // This will fold the two constants together, which may allow
4117 // other simplifications.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004118 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004119 CastOp->getOperand(0), I.getType(),
4120 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00004121 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00004122 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00004123 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00004124 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004125 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004126 } else if (CastOp->getOpcode() == Instruction::Or) {
4127 // Change: and (cast (or X, C1) to T), C2
4128 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00004129 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00004130 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4131 return ReplaceInstUsesWith(I, AndRHS);
4132 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004133 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004134 }
Chris Lattner06782f82003-07-23 19:36:21 +00004135 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004136
4137 // Try to fold constant and into select arguments.
4138 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004139 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004140 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004141 if (isa<PHINode>(Op0))
4142 if (Instruction *NV = FoldOpIntoPhi(I))
4143 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004144 }
4145
Chris Lattner8d969642003-03-10 23:06:50 +00004146 Value *Op0NotVal = dyn_castNotVal(Op0);
4147 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004148
Chris Lattner5b62aa72004-06-18 06:07:51 +00004149 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4150 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4151
Misha Brukmancb6267b2004-07-30 12:50:08 +00004152 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004153 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004154 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Chris Lattner48595f12004-06-10 02:07:29 +00004155 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004156 InsertNewInstBefore(Or, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004157 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004158 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004159
4160 {
Chris Lattner003b6202007-06-15 05:58:24 +00004161 Value *A = 0, *B = 0, *C = 0, *D = 0;
4162 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004163 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4164 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004165
4166 // (A|B) & ~(A&B) -> A^B
4167 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4168 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004169 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004170 }
4171 }
4172
4173 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004174 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4175 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004176
4177 // ~(A&B) & (A|B) -> A^B
4178 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4179 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004180 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004181 }
4182 }
Chris Lattner64daab52006-04-01 08:03:55 +00004183
4184 if (Op0->hasOneUse() &&
4185 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4186 if (A == Op1) { // (A^B)&A -> A&(A^B)
4187 I.swapOperands(); // Simplify below
4188 std::swap(Op0, Op1);
4189 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4190 cast<BinaryOperator>(Op0)->swapOperands();
4191 I.swapOperands(); // Simplify below
4192 std::swap(Op0, Op1);
4193 }
4194 }
4195 if (Op1->hasOneUse() &&
4196 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4197 if (B == Op0) { // B&(A^B) -> B&(B^A)
4198 cast<BinaryOperator>(Op1)->swapOperands();
4199 std::swap(A, B);
4200 }
4201 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004202 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Chris Lattner64daab52006-04-01 08:03:55 +00004203 InsertNewInstBefore(NotB, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004204 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattner64daab52006-04-01 08:03:55 +00004205 }
4206 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004207 }
4208
Reid Spencere4d87aa2006-12-23 06:05:41 +00004209 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4210 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4211 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004212 return R;
4213
Chris Lattner955f3312004-09-28 21:48:02 +00004214 Value *LHSVal, *RHSVal;
4215 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004216 ICmpInst::Predicate LHSCC, RHSCC;
4217 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4218 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4219 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4220 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4221 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4222 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4223 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00004224 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4225
4226 // Don't try to fold ICMP_SLT + ICMP_ULT.
4227 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4228 ICmpInst::isSignedPredicate(LHSCC) ==
4229 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00004230 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00004231 ICmpInst::Predicate GT;
4232 if (ICmpInst::isSignedPredicate(LHSCC) ||
4233 (ICmpInst::isEquality(LHSCC) &&
4234 ICmpInst::isSignedPredicate(RHSCC)))
4235 GT = ICmpInst::ICMP_SGT;
4236 else
4237 GT = ICmpInst::ICMP_UGT;
4238
Reid Spencere4d87aa2006-12-23 06:05:41 +00004239 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4240 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00004241 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00004242 std::swap(LHS, RHS);
4243 std::swap(LHSCst, RHSCst);
4244 std::swap(LHSCC, RHSCC);
4245 }
4246
Reid Spencere4d87aa2006-12-23 06:05:41 +00004247 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00004248 // comparing a value against two constants and and'ing the result
4249 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004250 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4251 // (from the FoldICmpLogical check above), that the two constants
4252 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00004253 assert(LHSCst != RHSCst && "Compares not folded above?");
4254
4255 switch (LHSCC) {
4256 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004257 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00004258 switch (RHSCC) {
4259 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004260 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4261 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4262 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004263 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004264 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4265 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4266 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00004267 return ReplaceInstUsesWith(I, LHS);
4268 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004269 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00004270 switch (RHSCC) {
4271 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 case ICmpInst::ICMP_ULT:
4273 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4274 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4275 break; // (X != 13 & X u< 15) -> no change
4276 case ICmpInst::ICMP_SLT:
4277 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4278 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4279 break; // (X != 13 & X s< 15) -> no change
4280 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4281 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4282 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00004283 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004284 case ICmpInst::ICMP_NE:
4285 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00004286 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004287 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattner955f3312004-09-28 21:48:02 +00004288 LHSVal->getName()+".off");
4289 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00004290 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4291 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00004292 }
4293 break; // (X != 13 & X != 15) -> no change
4294 }
4295 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004296 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00004297 switch (RHSCC) {
4298 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004299 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4300 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004301 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004302 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4303 break;
4304 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4305 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00004306 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004307 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4308 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004309 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004310 break;
4311 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00004312 switch (RHSCC) {
4313 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004314 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4315 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004316 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004317 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4318 break;
4319 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4320 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00004321 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004322 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4323 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004324 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004325 break;
4326 case ICmpInst::ICMP_UGT:
4327 switch (RHSCC) {
4328 default: assert(0 && "Unknown integer condition code!");
4329 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4330 return ReplaceInstUsesWith(I, LHS);
4331 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4332 return ReplaceInstUsesWith(I, RHS);
4333 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4334 break;
4335 case ICmpInst::ICMP_NE:
4336 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4337 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4338 break; // (X u> 13 & X != 15) -> no change
4339 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4340 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4341 true, I);
4342 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4343 break;
4344 }
4345 break;
4346 case ICmpInst::ICMP_SGT:
4347 switch (RHSCC) {
4348 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00004349 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00004350 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4351 return ReplaceInstUsesWith(I, RHS);
4352 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4353 break;
4354 case ICmpInst::ICMP_NE:
4355 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4356 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4357 break; // (X s> 13 & X != 15) -> no change
4358 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4359 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4360 true, I);
4361 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4362 break;
4363 }
4364 break;
Chris Lattner955f3312004-09-28 21:48:02 +00004365 }
4366 }
4367 }
4368
Chris Lattner6fc205f2006-05-05 06:39:07 +00004369 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004370 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4371 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4372 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4373 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004374 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004375 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004376 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4377 I.getType(), TD) &&
4378 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4379 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004380 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004381 Op1C->getOperand(0),
4382 I.getName());
4383 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004384 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004385 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004386 }
Chris Lattnere511b742006-11-14 07:46:50 +00004387
4388 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004389 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4390 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4391 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004392 SI0->getOperand(1) == SI1->getOperand(1) &&
4393 (SI0->hasOneUse() || SI1->hasOneUse())) {
4394 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004395 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004396 SI1->getOperand(0),
4397 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004398 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004399 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004400 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004401 }
4402
Chris Lattner99c65742007-10-24 05:38:08 +00004403 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4404 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4405 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4406 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4407 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4408 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4409 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4410 // If either of the constants are nans, then the whole thing returns
4411 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004412 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004413 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4414 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4415 RHS->getOperand(0));
4416 }
4417 }
4418 }
4419
Chris Lattner7e708292002-06-25 16:13:24 +00004420 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004421}
4422
Chris Lattnerafe91a52006-06-15 19:07:26 +00004423/// CollectBSwapParts - Look to see if the specified value defines a single byte
4424/// in the result. If it does, and if the specified byte hasn't been filled in
4425/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00004426static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427 Instruction *I = dyn_cast<Instruction>(V);
4428 if (I == 0) return true;
4429
4430 // If this is an or instruction, it is an inner node of the bswap.
4431 if (I->getOpcode() == Instruction::Or)
4432 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4433 CollectBSwapParts(I->getOperand(1), ByteValues);
4434
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004435 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004436 // If this is a shift by a constant int, and it is "24", then its operand
4437 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00004438 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004439 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004440 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00004441 8*(ByteValues.size()-1))
4442 return true;
4443
4444 unsigned DestNo;
4445 if (I->getOpcode() == Instruction::Shl) {
4446 // X << 24 defines the top byte with the lowest of the input bytes.
4447 DestNo = ByteValues.size()-1;
4448 } else {
4449 // X >>u 24 defines the low byte with the highest of the input bytes.
4450 DestNo = 0;
4451 }
4452
4453 // If the destination byte value is already defined, the values are or'd
4454 // together, which isn't a bswap (unless it's an or of the same bits).
4455 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4456 return true;
4457 ByteValues[DestNo] = I->getOperand(0);
4458 return false;
4459 }
4460
4461 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4462 // don't have this.
4463 Value *Shift = 0, *ShiftLHS = 0;
4464 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4465 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4466 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4467 return true;
4468 Instruction *SI = cast<Instruction>(Shift);
4469
4470 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004471 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4472 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00004473 return true;
4474
4475 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4476 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004477 if (AndAmt->getValue().getActiveBits() > 64)
4478 return true;
4479 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00004480 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004481 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004482 break;
4483 // Unknown mask for bswap.
4484 if (DestByte == ByteValues.size()) return true;
4485
Reid Spencerb83eb642006-10-20 07:07:24 +00004486 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004487 unsigned SrcByte;
4488 if (SI->getOpcode() == Instruction::Shl)
4489 SrcByte = DestByte - ShiftBytes;
4490 else
4491 SrcByte = DestByte + ShiftBytes;
4492
4493 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4494 if (SrcByte != ByteValues.size()-DestByte-1)
4495 return true;
4496
4497 // If the destination byte value is already defined, the values are or'd
4498 // together, which isn't a bswap (unless it's an or of the same bits).
4499 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4500 return true;
4501 ByteValues[DestByte] = SI->getOperand(0);
4502 return false;
4503}
4504
4505/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4506/// If so, insert the new bswap intrinsic and return it.
4507Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004508 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4509 if (!ITy || ITy->getBitWidth() % 16)
4510 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004511
4512 /// ByteValues - For each byte of the result, we keep track of which value
4513 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004514 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004515 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004516
4517 // Try to find all the pieces corresponding to the bswap.
4518 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4519 CollectBSwapParts(I.getOperand(1), ByteValues))
4520 return 0;
4521
4522 // Check to see if all of the bytes come from the same value.
4523 Value *V = ByteValues[0];
4524 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4525
4526 // Check to make sure that all of the bytes come from the same value.
4527 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4528 if (ByteValues[i] != V)
4529 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004530 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004531 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004532 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004533 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004534}
4535
4536
Chris Lattner7e708292002-06-25 16:13:24 +00004537Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004538 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004539 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004540
Chris Lattner42593e62007-03-24 23:56:43 +00004541 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004542 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004543
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004544 // or X, X = X
4545 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004546 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004547
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004548 // See if we can simplify any instructions used by the instruction whose sole
4549 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004550 if (!isa<VectorType>(I.getType())) {
4551 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4552 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4553 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4554 KnownZero, KnownOne))
4555 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004556 } else if (isa<ConstantAggregateZero>(Op1)) {
4557 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4558 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4559 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4560 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004561 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004562
4563
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004564
Chris Lattner3f5b8772002-05-06 16:14:14 +00004565 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004566 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004567 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004568 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4569 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004570 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004571 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004572 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004573 return BinaryOperator::CreateAnd(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004574 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004575 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004576
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004577 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4578 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004579 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004580 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004581 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004582 return BinaryOperator::CreateXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004583 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004584 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004585
4586 // Try to fold constant and into select arguments.
4587 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004588 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004589 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004590 if (isa<PHINode>(Op0))
4591 if (Instruction *NV = FoldOpIntoPhi(I))
4592 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004593 }
4594
Chris Lattner4f637d42006-01-06 17:59:59 +00004595 Value *A = 0, *B = 0;
4596 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004597
4598 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4599 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4600 return ReplaceInstUsesWith(I, Op1);
4601 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4602 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4603 return ReplaceInstUsesWith(I, Op0);
4604
Chris Lattner6423d4c2006-07-10 20:25:24 +00004605 // (A | B) | C and A | (B | C) -> bswap if possible.
4606 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004607 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004608 match(Op1, m_Or(m_Value(), m_Value())) ||
4609 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4610 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004611 if (Instruction *BSwap = MatchBSwap(I))
4612 return BSwap;
4613 }
4614
Chris Lattner6e4c6492005-05-09 04:58:36 +00004615 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4616 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004617 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004618 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004619 InsertNewInstBefore(NOr, I);
4620 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004621 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004622 }
4623
4624 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4625 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004626 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004627 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004628 InsertNewInstBefore(NOr, I);
4629 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004630 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004631 }
4632
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004633 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004634 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004635 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4636 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004637 Value *V1 = 0, *V2 = 0, *V3 = 0;
4638 C1 = dyn_cast<ConstantInt>(C);
4639 C2 = dyn_cast<ConstantInt>(D);
4640 if (C1 && C2) { // (A & C1)|(B & C2)
4641 // If we have: ((V + N) & C1) | (V & C2)
4642 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4643 // replace with V+N.
4644 if (C1->getValue() == ~C2->getValue()) {
4645 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4646 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4647 // Add commutes, try both ways.
4648 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4649 return ReplaceInstUsesWith(I, A);
4650 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4651 return ReplaceInstUsesWith(I, A);
4652 }
4653 // Or commutes, try both ways.
4654 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4655 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4656 // Add commutes, try both ways.
4657 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4658 return ReplaceInstUsesWith(I, B);
4659 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4660 return ReplaceInstUsesWith(I, B);
4661 }
4662 }
Chris Lattner044e5332007-04-08 08:01:49 +00004663 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004664 }
4665
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004666 // Check to see if we have any common things being and'ed. If so, find the
4667 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004668 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4669 if (A == B) // (A & C)|(A & D) == A & (C|D)
4670 V1 = A, V2 = C, V3 = D;
4671 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4672 V1 = A, V2 = B, V3 = C;
4673 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4674 V1 = C, V2 = A, V3 = D;
4675 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4676 V1 = C, V2 = A, V3 = B;
4677
4678 if (V1) {
4679 Value *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004680 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4681 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004682 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004683 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004684 }
Chris Lattnere511b742006-11-14 07:46:50 +00004685
4686 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004687 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4688 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4689 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004690 SI0->getOperand(1) == SI1->getOperand(1) &&
4691 (SI0->hasOneUse() || SI1->hasOneUse())) {
4692 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004693 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Chris Lattnere511b742006-11-14 07:46:50 +00004694 SI1->getOperand(0),
4695 SI0->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004696 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004697 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004698 }
4699 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004700
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004701 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4702 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004703 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004704 } else {
4705 A = 0;
4706 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004707 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004708 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4709 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004710 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004711
Misha Brukmancb6267b2004-07-30 12:50:08 +00004712 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004713 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004714 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004715 I.getName()+".demorgan"), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004716 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004717 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004718 }
Chris Lattnera2881962003-02-18 19:28:33 +00004719
Reid Spencere4d87aa2006-12-23 06:05:41 +00004720 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4721 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4722 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004723 return R;
4724
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004725 Value *LHSVal, *RHSVal;
4726 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004727 ICmpInst::Predicate LHSCC, RHSCC;
4728 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4729 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4730 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4731 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4732 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4733 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4734 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004735 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4736 // We can't fold (ugt x, C) | (sgt x, C2).
4737 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004738 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004739 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004740 bool NeedsSwap;
4741 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004742 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004743 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004744 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004745
4746 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004747 std::swap(LHS, RHS);
4748 std::swap(LHSCst, RHSCst);
4749 std::swap(LHSCC, RHSCC);
4750 }
4751
Reid Spencere4d87aa2006-12-23 06:05:41 +00004752 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004753 // comparing a value against two constants and or'ing the result
4754 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004755 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4756 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004757 // equal.
4758 assert(LHSCst != RHSCst && "Compares not folded above?");
4759
4760 switch (LHSCC) {
4761 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004762 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004763 switch (RHSCC) {
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 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4767 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004768 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004769 LHSVal->getName()+".off");
4770 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004771 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004772 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004773 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004774 break; // (X == 13 | X == 15) -> no change
4775 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4776 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004777 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004778 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4779 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4780 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004781 return ReplaceInstUsesWith(I, RHS);
4782 }
4783 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004784 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004785 switch (RHSCC) {
4786 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004787 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4788 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4789 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004790 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004791 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4792 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4793 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004794 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004795 }
4796 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004797 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004798 switch (RHSCC) {
4799 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004800 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004801 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004802 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004803 // If RHSCst is [us]MAXINT, it is always false. Not handling
4804 // this can cause overflow.
4805 if (RHSCst->isMaxValue(false))
4806 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004807 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4808 false, I);
4809 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4810 break;
4811 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4812 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004813 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004814 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4815 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004816 }
4817 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004818 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004819 switch (RHSCC) {
4820 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004821 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4822 break;
4823 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004824 // If RHSCst is [us]MAXINT, it is always false. Not handling
4825 // this can cause overflow.
4826 if (RHSCst->isMaxValue(true))
4827 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004828 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4829 false, I);
4830 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4831 break;
4832 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4833 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4834 return ReplaceInstUsesWith(I, RHS);
4835 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4836 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004837 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004838 break;
4839 case ICmpInst::ICMP_UGT:
4840 switch (RHSCC) {
4841 default: assert(0 && "Unknown integer condition code!");
4842 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4843 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4844 return ReplaceInstUsesWith(I, LHS);
4845 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4846 break;
4847 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4848 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004849 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004850 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4851 break;
4852 }
4853 break;
4854 case ICmpInst::ICMP_SGT:
4855 switch (RHSCC) {
4856 default: assert(0 && "Unknown integer condition code!");
4857 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4858 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4859 return ReplaceInstUsesWith(I, LHS);
4860 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4861 break;
4862 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4863 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004864 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004865 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4866 break;
4867 }
4868 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004869 }
4870 }
4871 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004872
4873 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004874 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004875 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004876 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004877 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4878 !isa<ICmpInst>(Op1C->getOperand(0))) {
4879 const Type *SrcTy = Op0C->getOperand(0)->getType();
4880 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4881 // Only do this if the casts both really cause code to be
4882 // generated.
4883 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4884 I.getType(), TD) &&
4885 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4886 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004887 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chengb98a10e2008-03-24 00:21:34 +00004888 Op1C->getOperand(0),
4889 I.getName());
4890 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004891 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004892 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004893 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004894 }
Chris Lattner99c65742007-10-24 05:38:08 +00004895 }
4896
4897
4898 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4899 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4900 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4901 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004902 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4903 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004904 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4905 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4906 // If either of the constants are nans, then the whole thing returns
4907 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004908 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004909 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4910
4911 // Otherwise, no need to compare the two constants, compare the
4912 // rest.
4913 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4914 RHS->getOperand(0));
4915 }
4916 }
4917 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004918
Chris Lattner7e708292002-06-25 16:13:24 +00004919 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004920}
4921
Dan Gohman844731a2008-05-13 00:00:25 +00004922namespace {
4923
Chris Lattnerc317d392004-02-16 01:20:27 +00004924// XorSelf - Implements: X ^ X --> 0
4925struct XorSelf {
4926 Value *RHS;
4927 XorSelf(Value *rhs) : RHS(rhs) {}
4928 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4929 Instruction *apply(BinaryOperator &Xor) const {
4930 return &Xor;
4931 }
4932};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004933
Dan Gohman844731a2008-05-13 00:00:25 +00004934}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004935
Chris Lattner7e708292002-06-25 16:13:24 +00004936Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004937 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004939
Evan Chengd34af782008-03-25 20:07:13 +00004940 if (isa<UndefValue>(Op1)) {
4941 if (isa<UndefValue>(Op0))
4942 // Handle undef ^ undef -> 0 special case. This is a common
4943 // idiom (misuse).
4944 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004945 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004946 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004947
Chris Lattnerc317d392004-02-16 01:20:27 +00004948 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4949 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004950 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004952 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004953
4954 // See if we can simplify any instructions used by the instruction whose sole
4955 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004956 if (!isa<VectorType>(I.getType())) {
4957 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4958 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4959 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4960 KnownZero, KnownOne))
4961 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004962 } else if (isa<ConstantAggregateZero>(Op1)) {
4963 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004964 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004965
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004966 // Is this a ~ operation?
4967 if (Value *NotOp = dyn_castNotVal(&I)) {
4968 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4969 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4970 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4971 if (Op0I->getOpcode() == Instruction::And ||
4972 Op0I->getOpcode() == Instruction::Or) {
4973 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4974 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4975 Instruction *NotY =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004976 BinaryOperator::CreateNot(Op0I->getOperand(1),
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004977 Op0I->getOperand(1)->getName()+".not");
4978 InsertNewInstBefore(NotY, I);
4979 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004980 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004981 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004982 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004983 }
4984 }
4985 }
4986 }
4987
4988
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004989 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004990 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4991 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4992 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004993 return new ICmpInst(ICI->getInversePredicate(),
4994 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004995
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004996 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4997 return new FCmpInst(FCI->getInversePredicate(),
4998 FCI->getOperand(0), FCI->getOperand(1));
4999 }
5000
Reid Spencere4d87aa2006-12-23 06:05:41 +00005001 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005002 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005003 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5004 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00005005 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5006 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005007 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005008 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005009 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005010
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005011 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005012 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005013 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005014 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00005015 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005016 return BinaryOperator::CreateSub(
Chris Lattner48595f12004-06-10 02:07:29 +00005017 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00005018 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00005019 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005020 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005021 // (X + C) ^ signbit -> (X + C + signbit)
5022 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005023 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005024
Chris Lattner7c4049c2004-01-12 19:35:11 +00005025 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005026 } else if (Op0I->getOpcode() == Instruction::Or) {
5027 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005028 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00005029 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5030 // Anything in both C1 and C2 is known to be zero, remove it from
5031 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005032 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005033 NewRHS = ConstantExpr::getAnd(NewRHS,
5034 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00005035 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005036 I.setOperand(0, Op0I->getOperand(0));
5037 I.setOperand(1, NewRHS);
5038 return &I;
5039 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005040 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005041 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005042 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005043
5044 // Try to fold constant and into select arguments.
5045 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005046 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005047 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005048 if (isa<PHINode>(Op0))
5049 if (Instruction *NV = FoldOpIntoPhi(I))
5050 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005051 }
5052
Chris Lattner8d969642003-03-10 23:06:50 +00005053 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005054 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005055 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005056
Chris Lattner8d969642003-03-10 23:06:50 +00005057 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005058 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005059 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005060
Chris Lattner318bf792007-03-18 22:51:34 +00005061
5062 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5063 if (Op1I) {
5064 Value *A, *B;
5065 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5066 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005067 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005068 I.swapOperands();
5069 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005070 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005071 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005072 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005073 }
Chris Lattner318bf792007-03-18 22:51:34 +00005074 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5075 if (Op0 == A) // A^(A^B) == B
5076 return ReplaceInstUsesWith(I, B);
5077 else if (Op0 == B) // A^(B^A) == B
5078 return ReplaceInstUsesWith(I, A);
5079 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005080 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005081 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005082 std::swap(A, B);
5083 }
Chris Lattner318bf792007-03-18 22:51:34 +00005084 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005085 I.swapOperands(); // Simplified below.
5086 std::swap(Op0, Op1);
5087 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005088 }
Chris Lattner318bf792007-03-18 22:51:34 +00005089 }
5090
5091 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5092 if (Op0I) {
5093 Value *A, *B;
5094 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5095 if (A == Op1) // (B|A)^B == (A|B)^B
5096 std::swap(A, B);
5097 if (B == Op1) { // (A|B)^B == A & ~B
5098 Instruction *NotB =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005099 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5100 return BinaryOperator::CreateAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00005101 }
Chris Lattner318bf792007-03-18 22:51:34 +00005102 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5103 if (Op1 == A) // (A^B)^A == B
5104 return ReplaceInstUsesWith(I, B);
5105 else if (Op1 == B) // (B^A)^A == B
5106 return ReplaceInstUsesWith(I, A);
5107 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5108 if (A == Op1) // (A&B)^A -> (B&A)^A
5109 std::swap(A, B);
5110 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005111 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00005112 Instruction *N =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005113 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5114 return BinaryOperator::CreateAnd(N, Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005115 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005116 }
Chris Lattner318bf792007-03-18 22:51:34 +00005117 }
5118
5119 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5120 if (Op0I && Op1I && Op0I->isShift() &&
5121 Op0I->getOpcode() == Op1I->getOpcode() &&
5122 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5123 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5124 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005125 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Chris Lattner318bf792007-03-18 22:51:34 +00005126 Op1I->getOperand(0),
5127 Op0I->getName()), I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005128 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005129 Op1I->getOperand(1));
5130 }
5131
5132 if (Op0I && Op1I) {
5133 Value *A, *B, *C, *D;
5134 // (A & B)^(A | B) -> A ^ B
5135 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5136 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5137 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005138 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005139 }
5140 // (A | B)^(A & B) -> A ^ B
5141 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5142 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5143 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005144 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005145 }
5146
5147 // (A & B)^(C & D)
5148 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5149 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5150 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5151 // (X & Y)^(X & Y) -> (Y^Z) & X
5152 Value *X = 0, *Y = 0, *Z = 0;
5153 if (A == C)
5154 X = A, Y = B, Z = D;
5155 else if (A == D)
5156 X = A, Y = B, Z = C;
5157 else if (B == C)
5158 X = B, Y = A, Z = D;
5159 else if (B == D)
5160 X = B, Y = A, Z = C;
5161
5162 if (X) {
5163 Instruction *NewOp =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005164 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5165 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005166 }
5167 }
5168 }
5169
Reid Spencere4d87aa2006-12-23 06:05:41 +00005170 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5171 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5172 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005173 return R;
5174
Chris Lattner6fc205f2006-05-05 06:39:07 +00005175 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005176 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005177 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005178 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5179 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005180 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005181 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005182 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5183 I.getType(), TD) &&
5184 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5185 I.getType(), TD)) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005186 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005187 Op1C->getOperand(0),
5188 I.getName());
5189 InsertNewInstBefore(NewOp, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005190 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005191 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005192 }
Chris Lattner99c65742007-10-24 05:38:08 +00005193 }
Chris Lattner7e708292002-06-25 16:13:24 +00005194 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005195}
5196
Chris Lattnera96879a2004-09-29 17:40:11 +00005197/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5198/// overflowed for this type.
5199static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00005200 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005201 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00005202
Reid Spencere4e40032007-03-21 23:19:50 +00005203 if (IsSigned)
5204 if (In2->getValue().isNegative())
5205 return Result->getValue().sgt(In1->getValue());
5206 else
5207 return Result->getValue().slt(In1->getValue());
5208 else
5209 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005210}
5211
Chris Lattner574da9b2005-01-13 20:14:25 +00005212/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5213/// code necessary to compute the offset from the base pointer (without adding
5214/// in the base pointer). Return the result as a signed integer of intptr size.
5215static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5216 TargetData &TD = IC.getTargetData();
5217 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005218 const Type *IntPtrTy = TD.getIntPtrType();
5219 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005220
5221 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005222 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005223 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005224
Chris Lattner574da9b2005-01-13 20:14:25 +00005225 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5226 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00005227 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005228 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5229 if (OpC->isZero()) continue;
5230
5231 // Handle a struct index, which adds its field offset to the pointer.
5232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5234
5235 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5236 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00005237 else
Chris Lattnere62f0212007-04-28 04:52:43 +00005238 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005239 BinaryOperator::CreateAdd(Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005240 ConstantInt::get(IntPtrTy, Size),
5241 GEP->getName()+".offs"), I);
5242 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005243 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005244
5245 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5246 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5247 Scale = ConstantExpr::getMul(OC, Scale);
5248 if (Constant *RC = dyn_cast<Constant>(Result))
5249 Result = ConstantExpr::getAdd(RC, Scale);
5250 else {
5251 // Emit an add instruction.
5252 Result = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005253 BinaryOperator::CreateAdd(Result, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005254 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00005255 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005256 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005257 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005258 // Convert to correct type.
5259 if (Op->getType() != IntPtrTy) {
5260 if (Constant *OpC = dyn_cast<Constant>(Op))
5261 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5262 else
5263 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5264 Op->getName()+".c"), I);
5265 }
5266 if (Size != 1) {
5267 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5268 if (Constant *OpC = dyn_cast<Constant>(Op))
5269 Op = ConstantExpr::getMul(OpC, Scale);
5270 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005271 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Chris Lattnere62f0212007-04-28 04:52:43 +00005272 GEP->getName()+".idx"), I);
5273 }
5274
5275 // Emit an add instruction.
5276 if (isa<Constant>(Op) && isa<Constant>(Result))
5277 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5278 cast<Constant>(Result));
5279 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005280 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Chris Lattnere62f0212007-04-28 04:52:43 +00005281 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00005282 }
5283 return Result;
5284}
5285
Chris Lattner10c0d912008-04-22 02:53:33 +00005286
5287/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5288/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5289/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5290/// complex, and scales are involved. The above expression would also be legal
5291/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5292/// later form is less amenable to optimization though, and we are allowed to
5293/// generate the first by knowing that pointer arithmetic doesn't overflow.
5294///
5295/// If we can't emit an optimized form for this expression, this returns null.
5296///
5297static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5298 InstCombiner &IC) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005299 TargetData &TD = IC.getTargetData();
5300 gep_type_iterator GTI = gep_type_begin(GEP);
5301
5302 // Check to see if this gep only has a single variable index. If so, and if
5303 // any constant indices are a multiple of its scale, then we can compute this
5304 // in terms of the scale of the variable index. For example, if the GEP
5305 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5306 // because the expression will cross zero at the same point.
5307 unsigned i, e = GEP->getNumOperands();
5308 int64_t Offset = 0;
5309 for (i = 1; i != e; ++i, ++GTI) {
5310 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5311 // Compute the aggregate offset of constant indices.
5312 if (CI->isZero()) continue;
5313
5314 // Handle a struct index, which adds its field offset to the pointer.
5315 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5316 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5317 } else {
5318 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5319 Offset += Size*CI->getSExtValue();
5320 }
5321 } else {
5322 // Found our variable index.
5323 break;
5324 }
5325 }
5326
5327 // If there are no variable indices, we must have a constant offset, just
5328 // evaluate it the general way.
5329 if (i == e) return 0;
5330
5331 Value *VariableIdx = GEP->getOperand(i);
5332 // Determine the scale factor of the variable element. For example, this is
5333 // 4 if the variable index is into an array of i32.
5334 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5335
5336 // Verify that there are no other variable indices. If so, emit the hard way.
5337 for (++i, ++GTI; i != e; ++i, ++GTI) {
5338 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5339 if (!CI) return 0;
5340
5341 // Compute the aggregate offset of constant indices.
5342 if (CI->isZero()) continue;
5343
5344 // Handle a struct index, which adds its field offset to the pointer.
5345 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5346 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5347 } else {
5348 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5349 Offset += Size*CI->getSExtValue();
5350 }
5351 }
5352
5353 // Okay, we know we have a single variable index, which must be a
5354 // pointer/array/vector index. If there is no offset, life is simple, return
5355 // the index.
5356 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5357 if (Offset == 0) {
5358 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5359 // we don't need to bother extending: the extension won't affect where the
5360 // computation crosses zero.
5361 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5362 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5363 VariableIdx->getNameStart(), &I);
5364 return VariableIdx;
5365 }
5366
5367 // Otherwise, there is an index. The computation we will do will be modulo
5368 // the pointer size, so get it.
5369 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5370
5371 Offset &= PtrSizeMask;
5372 VariableScale &= PtrSizeMask;
5373
5374 // To do this transformation, any constant index must be a multiple of the
5375 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5376 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5377 // multiple of the variable scale.
5378 int64_t NewOffs = Offset / (int64_t)VariableScale;
5379 if (Offset != NewOffs*(int64_t)VariableScale)
5380 return 0;
5381
5382 // Okay, we can do this evaluation. Start by converting the index to intptr.
5383 const Type *IntPtrTy = TD.getIntPtrType();
5384 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005385 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005386 true /*SExt*/,
5387 VariableIdx->getNameStart(), &I);
5388 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005389 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005390}
5391
5392
Reid Spencere4d87aa2006-12-23 06:05:41 +00005393/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005394/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005395Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5396 ICmpInst::Predicate Cond,
5397 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00005398 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00005399
Chris Lattner10c0d912008-04-22 02:53:33 +00005400 // Look through bitcasts.
5401 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5402 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005403
Chris Lattner574da9b2005-01-13 20:14:25 +00005404 Value *PtrBase = GEPLHS->getOperand(0);
5405 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005406 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005407 // This transformation (ignoring the base and scales) is valid because we
5408 // know pointers can't overflow. See if we can output an optimized form.
5409 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5410
5411 // If not, synthesize the offset the hard way.
5412 if (Offset == 0)
5413 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattner7c95deb2008-02-05 04:45:32 +00005414 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5415 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00005416 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005417 // If the base pointers are different, but the indices are the same, just
5418 // compare the base pointer.
5419 if (PtrBase != GEPRHS->getOperand(0)) {
5420 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005421 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005422 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005423 if (IndicesTheSame)
5424 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5425 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5426 IndicesTheSame = false;
5427 break;
5428 }
5429
5430 // If all indices are the same, just compare the base pointers.
5431 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005432 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5433 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005434
5435 // Otherwise, the base pointers are different and the indices are
5436 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005437 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005438 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005439
Chris Lattnere9d782b2005-01-13 22:25:21 +00005440 // If one of the GEPs has all zero indices, recurse.
5441 bool AllZeros = true;
5442 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5443 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5444 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5445 AllZeros = false;
5446 break;
5447 }
5448 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005449 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5450 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005451
5452 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005453 AllZeros = true;
5454 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5455 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5456 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5457 AllZeros = false;
5458 break;
5459 }
5460 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005461 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005462
Chris Lattner4401c9c2005-01-14 00:20:05 +00005463 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5464 // If the GEPs only differ by one index, compare it.
5465 unsigned NumDifferences = 0; // Keep track of # differences.
5466 unsigned DiffOperand = 0; // The operand that differs.
5467 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5468 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005469 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5470 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005471 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005472 NumDifferences = 2;
5473 break;
5474 } else {
5475 if (NumDifferences++) break;
5476 DiffOperand = i;
5477 }
5478 }
5479
5480 if (NumDifferences == 0) // SAME GEP?
5481 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00005482 ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005483 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005484
Chris Lattner4401c9c2005-01-14 00:20:05 +00005485 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005486 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5487 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005488 // Make sure we do a signed comparison here.
5489 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005490 }
5491 }
5492
Reid Spencere4d87aa2006-12-23 06:05:41 +00005493 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005494 // the result to fold to a constant!
5495 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5496 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5497 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5498 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5499 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005500 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005501 }
5502 }
5503 return 0;
5504}
5505
Chris Lattnera5406232008-05-19 20:18:56 +00005506/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5507///
5508Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5509 Instruction *LHSI,
5510 Constant *RHSC) {
5511 if (!isa<ConstantFP>(RHSC)) return 0;
5512 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5513
5514 // Get the width of the mantissa. We don't want to hack on conversions that
5515 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005516 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005517 if (MantissaWidth == -1) return 0; // Unknown.
5518
5519 // Check to see that the input is converted from an integer type that is small
5520 // enough that preserves all bits. TODO: check here for "known" sign bits.
5521 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5522 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5523
5524 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5525 if (isa<UIToFPInst>(LHSI))
5526 ++InputSize;
5527
5528 // If the conversion would lose info, don't hack on this.
5529 if ((int)InputSize > MantissaWidth)
5530 return 0;
5531
5532 // Otherwise, we can potentially simplify the comparison. We know that it
5533 // will always come through as an integer value and we know the constant is
5534 // not a NAN (it would have been previously simplified).
5535 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5536
5537 ICmpInst::Predicate Pred;
5538 switch (I.getPredicate()) {
5539 default: assert(0 && "Unexpected predicate!");
5540 case FCmpInst::FCMP_UEQ:
5541 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5542 case FCmpInst::FCMP_UGT:
5543 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5544 case FCmpInst::FCMP_UGE:
5545 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5546 case FCmpInst::FCMP_ULT:
5547 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5548 case FCmpInst::FCMP_ULE:
5549 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5550 case FCmpInst::FCMP_UNE:
5551 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5552 case FCmpInst::FCMP_ORD:
5553 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5554 case FCmpInst::FCMP_UNO:
5555 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5556 }
5557
5558 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5559
5560 // Now we know that the APFloat is a normal number, zero or inf.
5561
Chris Lattner85162782008-05-20 03:50:52 +00005562 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005563 // comparing an i8 to 300.0.
5564 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5565
5566 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5567 // and large values.
5568 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5569 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5570 APFloat::rmNearestTiesToEven);
5571 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5572 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5573 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5574 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5575 }
5576
5577 // See if the RHS value is < SignedMin.
5578 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5579 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5580 APFloat::rmNearestTiesToEven);
5581 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5582 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5583 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5584 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5585 }
5586
5587 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5588 // it may still be fractional. See if it is fractional by casting the FP
5589 // value to the integer value and back, checking for equality. Don't do this
5590 // for zero, because -0.0 is not fractional.
5591 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5592 if (!RHS.isZero() &&
5593 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5594 // If we had a comparison against a fractional value, we have to adjust
5595 // the compare predicate and sometimes the value. RHSC is rounded towards
5596 // zero at this point.
5597 switch (Pred) {
5598 default: assert(0 && "Unexpected integer comparison!");
5599 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5600 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5601 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5602 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5603 case ICmpInst::ICMP_SLE:
5604 // (float)int <= 4.4 --> int <= 4
5605 // (float)int <= -4.4 --> int < -4
5606 if (RHS.isNegative())
5607 Pred = ICmpInst::ICMP_SLT;
5608 break;
5609 case ICmpInst::ICMP_SLT:
5610 // (float)int < -4.4 --> int < -4
5611 // (float)int < 4.4 --> int <= 4
5612 if (!RHS.isNegative())
5613 Pred = ICmpInst::ICMP_SLE;
5614 break;
5615 case ICmpInst::ICMP_SGT:
5616 // (float)int > 4.4 --> int > 4
5617 // (float)int > -4.4 --> int >= -4
5618 if (RHS.isNegative())
5619 Pred = ICmpInst::ICMP_SGE;
5620 break;
5621 case ICmpInst::ICMP_SGE:
5622 // (float)int >= -4.4 --> int >= -4
5623 // (float)int >= 4.4 --> int > 4
5624 if (!RHS.isNegative())
5625 Pred = ICmpInst::ICMP_SGT;
5626 break;
5627 }
5628 }
5629
5630 // Lower this FP comparison into an appropriate integer version of the
5631 // comparison.
5632 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5633}
5634
Reid Spencere4d87aa2006-12-23 06:05:41 +00005635Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5636 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005638
Chris Lattner58e97462007-01-14 19:42:17 +00005639 // Fold trivial predicates.
5640 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5641 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5642 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5643 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5644
5645 // Simplify 'fcmp pred X, X'
5646 if (Op0 == Op1) {
5647 switch (I.getPredicate()) {
5648 default: assert(0 && "Unknown predicate!");
5649 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5650 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5651 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5652 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5653 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5654 case FCmpInst::FCMP_OLT: // True if ordered and less than
5655 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5656 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5657
5658 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5659 case FCmpInst::FCMP_ULT: // True if unordered or less than
5660 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5661 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5662 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5663 I.setPredicate(FCmpInst::FCMP_UNO);
5664 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5665 return &I;
5666
5667 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5668 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5669 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5670 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5671 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5672 I.setPredicate(FCmpInst::FCMP_ORD);
5673 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5674 return &I;
5675 }
5676 }
5677
Reid Spencere4d87aa2006-12-23 06:05:41 +00005678 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005679 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00005680
Reid Spencere4d87aa2006-12-23 06:05:41 +00005681 // Handle fcmp with constant RHS
5682 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005683 // If the constant is a nan, see if we can fold the comparison based on it.
5684 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5685 if (CFP->getValueAPF().isNaN()) {
5686 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5687 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
Chris Lattner85162782008-05-20 03:50:52 +00005688 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5689 "Comparison must be either ordered or unordered!");
5690 // True if unordered.
5691 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
Chris Lattnera5406232008-05-19 20:18:56 +00005692 }
5693 }
5694
Reid Spencere4d87aa2006-12-23 06:05:41 +00005695 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5696 switch (LHSI->getOpcode()) {
5697 case Instruction::PHI:
5698 if (Instruction *NV = FoldOpIntoPhi(I))
5699 return NV;
5700 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005701 case Instruction::SIToFP:
5702 case Instruction::UIToFP:
5703 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5704 return NV;
5705 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005706 case Instruction::Select:
5707 // If either operand of the select is a constant, we can fold the
5708 // comparison into the select arms, which will cause one to be
5709 // constant folded and the select turned into a bitwise or.
5710 Value *Op1 = 0, *Op2 = 0;
5711 if (LHSI->hasOneUse()) {
5712 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5713 // Fold the known value into the constant operand.
5714 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5715 // Insert a new FCmp of the other select operand.
5716 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5717 LHSI->getOperand(2), RHSC,
5718 I.getName()), I);
5719 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5720 // Fold the known value into the constant operand.
5721 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5722 // Insert a new FCmp of the other select operand.
5723 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5724 LHSI->getOperand(1), RHSC,
5725 I.getName()), I);
5726 }
5727 }
5728
5729 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005730 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005731 break;
5732 }
5733 }
5734
5735 return Changed ? &I : 0;
5736}
5737
5738Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5739 bool Changed = SimplifyCompare(I);
5740 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5741 const Type *Ty = Op0->getType();
5742
5743 // icmp X, X
5744 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00005745 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005746 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005747
5748 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00005749 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005750
Reid Spencere4d87aa2006-12-23 06:05:41 +00005751 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005752 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005753 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5754 isa<ConstantPointerNull>(Op0)) &&
5755 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005756 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00005757 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005758 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005759
Reid Spencere4d87aa2006-12-23 06:05:41 +00005760 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00005761 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005762 switch (I.getPredicate()) {
5763 default: assert(0 && "Invalid icmp instruction!");
5764 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005765 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00005766 InsertNewInstBefore(Xor, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005767 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005768 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005769 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005770 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005771
Reid Spencere4d87aa2006-12-23 06:05:41 +00005772 case ICmpInst::ICMP_UGT:
5773 case ICmpInst::ICMP_SGT:
5774 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005775 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005776 case ICmpInst::ICMP_ULT:
5777 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005778 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005779 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005780 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005781 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005782 case ICmpInst::ICMP_UGE:
5783 case ICmpInst::ICMP_SGE:
5784 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005785 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005786 case ICmpInst::ICMP_ULE:
5787 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005788 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Chris Lattner5dbef222004-08-11 00:50:51 +00005789 InsertNewInstBefore(Not, I);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005790 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005791 }
5792 }
Chris Lattner8b170942002-08-09 23:47:40 +00005793 }
5794
Chris Lattner2be51ae2004-06-09 04:24:29 +00005795 // See if we are doing a comparison between a constant and an instruction that
5796 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005797 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005798 Value *A, *B;
5799
Chris Lattnerb6566012008-01-05 01:18:20 +00005800 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5801 if (I.isEquality() && CI->isNullValue() &&
5802 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5803 // (icmp cond A B) if cond is equality
5804 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005805 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005806
Reid Spencere4d87aa2006-12-23 06:05:41 +00005807 switch (I.getPredicate()) {
5808 default: break;
5809 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5810 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005811 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005812 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5813 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5814 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5815 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005816 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5817 if (CI->isMinValue(true))
5818 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5819 ConstantInt::getAllOnesValue(Op0->getType()));
5820
Reid Spencere4d87aa2006-12-23 06:05:41 +00005821 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005822
Reid Spencere4d87aa2006-12-23 06:05:41 +00005823 case ICmpInst::ICMP_SLT:
5824 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005825 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005826 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5827 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5828 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5829 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5830 break;
5831
5832 case ICmpInst::ICMP_UGT:
5833 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005834 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005835 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5836 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5837 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5838 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005839
5840 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5841 if (CI->isMaxValue(true))
5842 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5843 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005844 break;
5845
5846 case ICmpInst::ICMP_SGT:
5847 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005848 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005849 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5850 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5851 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5852 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5853 break;
5854
5855 case ICmpInst::ICMP_ULE:
5856 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005857 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005858 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5859 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5860 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5861 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5862 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005863
Reid Spencere4d87aa2006-12-23 06:05:41 +00005864 case ICmpInst::ICMP_SLE:
5865 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005866 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005867 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5868 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5869 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5870 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5871 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005872
Reid Spencere4d87aa2006-12-23 06:05:41 +00005873 case ICmpInst::ICMP_UGE:
5874 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005875 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5877 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5878 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5879 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5880 break;
5881
5882 case ICmpInst::ICMP_SGE:
5883 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005885 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5886 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5887 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5888 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5889 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005890 }
5891
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 // If we still have a icmp le or icmp ge instruction, turn it into the
5893 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005894 // already been handled above, this requires little checking.
5895 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005896 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005897 default: break;
5898 case ICmpInst::ICMP_ULE:
5899 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5900 case ICmpInst::ICMP_SLE:
5901 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5902 case ICmpInst::ICMP_UGE:
5903 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5904 case ICmpInst::ICMP_SGE:
5905 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005906 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005907
5908 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005909 // in the input. If this comparison is a normal comparison, it demands all
5910 // bits, if it is a sign bit comparison, it only demands the sign bit.
5911
5912 bool UnusedBit;
5913 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5914
Reid Spencer0460fb32007-03-22 20:36:03 +00005915 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5916 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005917 if (SimplifyDemandedBits(Op0,
5918 isSignBit ? APInt::getSignBit(BitWidth)
5919 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005920 KnownZero, KnownOne, 0))
5921 return &I;
5922
5923 // Given the known and unknown bits, compute a range that the LHS could be
5924 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005925 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005926 // Compute the Min, Max and RHS values based on the known bits. For the
5927 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005928 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5929 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005930 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005931 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5932 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005933 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005934 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5935 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005936 }
5937 switch (I.getPredicate()) { // LE/GE have been folded already.
5938 default: assert(0 && "Unknown icmp opcode!");
5939 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005940 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005941 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005942 break;
5943 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005944 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005945 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 break;
5947 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005948 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005949 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005950 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005951 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005952 break;
5953 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005954 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005955 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005956 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005957 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005958 break;
5959 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005960 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005961 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005962 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005963 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005964 break;
5965 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005966 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005967 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005968 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005969 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005970 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005971 }
5972 }
5973
Reid Spencere4d87aa2006-12-23 06:05:41 +00005974 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005975 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005976 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005977 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005978 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5979 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005980 }
5981
Chris Lattner01deb9d2007-04-03 17:43:25 +00005982 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005983 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5984 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5985 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005986 case Instruction::GetElementPtr:
5987 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005988 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005989 bool isAllZeros = true;
5990 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5991 if (!isa<Constant>(LHSI->getOperand(i)) ||
5992 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5993 isAllZeros = false;
5994 break;
5995 }
5996 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005997 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005998 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5999 }
6000 break;
6001
Chris Lattner6970b662005-04-23 15:31:55 +00006002 case Instruction::PHI:
6003 if (Instruction *NV = FoldOpIntoPhi(I))
6004 return NV;
6005 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006006 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006007 // If either operand of the select is a constant, we can fold the
6008 // comparison into the select arms, which will cause one to be
6009 // constant folded and the select turned into a bitwise or.
6010 Value *Op1 = 0, *Op2 = 0;
6011 if (LHSI->hasOneUse()) {
6012 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6013 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006014 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6015 // Insert a new ICmp of the other select operand.
6016 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6017 LHSI->getOperand(2), RHSC,
6018 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006019 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6020 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006021 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6022 // Insert a new ICmp of the other select operand.
6023 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6024 LHSI->getOperand(1), RHSC,
6025 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00006026 }
6027 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006028
Chris Lattner6970b662005-04-23 15:31:55 +00006029 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006030 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006031 break;
6032 }
Chris Lattner4802d902007-04-06 18:57:34 +00006033 case Instruction::Malloc:
6034 // If we have (malloc != null), and if the malloc has a single use, we
6035 // can assume it is successful and remove the malloc.
6036 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6037 AddToWorkList(LHSI);
6038 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006039 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006040 }
6041 break;
6042 }
Chris Lattner6970b662005-04-23 15:31:55 +00006043 }
6044
Reid Spencere4d87aa2006-12-23 06:05:41 +00006045 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00006046 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006047 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006048 return NI;
6049 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006050 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6051 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006052 return NI;
6053
Reid Spencere4d87aa2006-12-23 06:05:41 +00006054 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006055 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6056 // now.
6057 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6058 if (isa<PointerType>(Op0->getType()) &&
6059 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006060 // We keep moving the cast from the left operand over to the right
6061 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006062 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006063
Chris Lattner57d86372007-01-06 01:45:59 +00006064 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6065 // so eliminate it as well.
6066 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6067 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006068
Chris Lattnerde90b762003-11-03 04:25:02 +00006069 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006070 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006071 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00006072 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006073 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006074 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006075 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006076 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006077 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006078 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006079 }
Chris Lattner57d86372007-01-06 01:45:59 +00006080 }
6081
6082 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006083 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006084 // This comes up when you have code like
6085 // int X = A < B;
6086 // if (X) ...
6087 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006088 // with a constant or another cast from the same type.
6089 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006090 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006091 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006092 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006093
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006094 // ~x < ~y --> y < x
6095 { Value *A, *B;
6096 if (match(Op0, m_Not(m_Value(A))) &&
6097 match(Op1, m_Not(m_Value(B))))
6098 return new ICmpInst(I.getPredicate(), B, A);
6099 }
6100
Chris Lattner65b72ba2006-09-18 04:22:48 +00006101 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006102 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006103
6104 // -x == -y --> x == y
6105 if (match(Op0, m_Neg(m_Value(A))) &&
6106 match(Op1, m_Neg(m_Value(B))))
6107 return new ICmpInst(I.getPredicate(), A, B);
6108
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006109 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6110 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6111 Value *OtherVal = A == Op1 ? B : A;
6112 return new ICmpInst(I.getPredicate(), OtherVal,
6113 Constant::getNullValue(A->getType()));
6114 }
6115
6116 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6117 // A^c1 == C^c2 --> A == C^(c1^c2)
6118 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6119 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6120 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006121 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006122 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006123 return new ICmpInst(I.getPredicate(), A,
6124 InsertNewInstBefore(Xor, I));
6125 }
6126
6127 // A^B == A^D -> B == D
6128 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6129 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6130 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6131 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6132 }
6133 }
6134
6135 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6136 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006137 // A == (A^B) -> B == 0
6138 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006139 return new ICmpInst(I.getPredicate(), OtherVal,
6140 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006141 }
6142 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006143 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006144 return new ICmpInst(I.getPredicate(), B,
6145 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006146 }
6147 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006148 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00006149 return new ICmpInst(I.getPredicate(), B,
6150 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00006151 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00006152
Chris Lattner9c2328e2006-11-14 06:06:06 +00006153 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6154 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6155 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6156 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6157 Value *X = 0, *Y = 0, *Z = 0;
6158
6159 if (A == C) {
6160 X = B; Y = D; Z = A;
6161 } else if (A == D) {
6162 X = B; Y = C; Z = A;
6163 } else if (B == C) {
6164 X = A; Y = D; Z = B;
6165 } else if (B == D) {
6166 X = A; Y = C; Z = B;
6167 }
6168
6169 if (X) { // Build (X^Y) & Z
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006170 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6171 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Chris Lattner9c2328e2006-11-14 06:06:06 +00006172 I.setOperand(0, Op1);
6173 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6174 return &I;
6175 }
6176 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006177 }
Chris Lattner7e708292002-06-25 16:13:24 +00006178 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006179}
6180
Chris Lattner562ef782007-06-20 23:46:26 +00006181
6182/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6183/// and CmpRHS are both known to be integer constants.
6184Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6185 ConstantInt *DivRHS) {
6186 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6187 const APInt &CmpRHSV = CmpRHS->getValue();
6188
6189 // FIXME: If the operand types don't match the type of the divide
6190 // then don't attempt this transform. The code below doesn't have the
6191 // logic to deal with a signed divide and an unsigned compare (and
6192 // vice versa). This is because (x /s C1) <s C2 produces different
6193 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6194 // (x /u C1) <u C2. Simply casting the operands and result won't
6195 // work. :( The if statement below tests that condition and bails
6196 // if it finds it.
6197 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6198 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6199 return 0;
6200 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006201 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00006202
6203 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6204 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6205 // C2 (CI). By solving for X we can turn this into a range check
6206 // instead of computing a divide.
6207 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6208
6209 // Determine if the product overflows by seeing if the product is
6210 // not equal to the divide. Make sure we do the same kind of divide
6211 // as in the LHS instruction that we're folding.
6212 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6213 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6214
6215 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006216 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006217
Chris Lattner1dbfd482007-06-21 18:11:19 +00006218 // Figure out the interval that is being checked. For example, a comparison
6219 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6220 // Compute this interval based on the constants involved and the signedness of
6221 // the compare/divide. This computes a half-open interval, keeping track of
6222 // whether either value in the interval overflows. After analysis each
6223 // overflow variable is set to 0 if it's corresponding bound variable is valid
6224 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6225 int LoOverflow = 0, HiOverflow = 0;
6226 ConstantInt *LoBound = 0, *HiBound = 0;
6227
6228
Chris Lattner562ef782007-06-20 23:46:26 +00006229 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006230 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006231 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006232 HiOverflow = LoOverflow = ProdOV;
6233 if (!HiOverflow)
6234 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00006235 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006236 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006237 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00006238 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6239 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006240 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006241 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6242 HiOverflow = LoOverflow = ProdOV;
6243 if (!HiOverflow)
6244 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006245 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006246 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00006247 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6248 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00006249 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006250 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006251 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006252 }
Dan Gohman76491272008-02-13 22:09:18 +00006253 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006254 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006255 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00006256 LoBound = AddOne(DivRHS);
6257 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006258 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6259 HiOverflow = 1; // [INTMIN+1, overflow)
6260 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6261 }
Dan Gohman76491272008-02-13 22:09:18 +00006262 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006263 // e.g. X/-5 op 3 --> [-19, -14)
6264 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006265 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006266 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00006267 HiBound = AddOne(Prod);
6268 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006269 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006270 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006271 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006272 HiBound = Subtract(Prod, DivRHS);
6273 }
6274
Chris Lattner1dbfd482007-06-21 18:11:19 +00006275 // Dividing by a negative swaps the condition. LT <-> GT
6276 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006277 }
6278
6279 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006280 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00006281 default: assert(0 && "Unhandled icmp opcode!");
6282 case ICmpInst::ICMP_EQ:
6283 if (LoOverflow && HiOverflow)
6284 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6285 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006286 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006287 ICmpInst::ICMP_UGE, X, LoBound);
6288 else if (LoOverflow)
6289 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6290 ICmpInst::ICMP_ULT, X, HiBound);
6291 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006292 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006293 case ICmpInst::ICMP_NE:
6294 if (LoOverflow && HiOverflow)
6295 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6296 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00006297 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006298 ICmpInst::ICMP_ULT, X, LoBound);
6299 else if (LoOverflow)
6300 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6301 ICmpInst::ICMP_UGE, X, HiBound);
6302 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006303 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006304 case ICmpInst::ICMP_ULT:
6305 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006306 if (LoOverflow == +1) // Low bound is greater than input range.
6307 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6308 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006309 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006310 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006311 case ICmpInst::ICMP_UGT:
6312 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006313 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00006314 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00006315 else if (HiOverflow == -1) // High bound less than input range.
6316 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6317 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00006318 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6319 else
6320 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6321 }
6322}
6323
6324
Chris Lattner01deb9d2007-04-03 17:43:25 +00006325/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6326///
6327Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6328 Instruction *LHSI,
6329 ConstantInt *RHS) {
6330 const APInt &RHSV = RHS->getValue();
6331
6332 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00006333 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006334 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6335 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6336 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006337 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6338 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006339 Value *CompareVal = LHSI->getOperand(0);
6340
6341 // If the sign bit of the XorCST is not set, there is no change to
6342 // the operation, just stop using the Xor.
6343 if (!XorCST->getValue().isNegative()) {
6344 ICI.setOperand(0, CompareVal);
6345 AddToWorkList(LHSI);
6346 return &ICI;
6347 }
6348
6349 // Was the old condition true if the operand is positive?
6350 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6351
6352 // If so, the new one isn't.
6353 isTrueIfPositive ^= true;
6354
6355 if (isTrueIfPositive)
6356 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6357 else
6358 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6359 }
6360 }
6361 break;
6362 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6363 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6364 LHSI->getOperand(0)->hasOneUse()) {
6365 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6366
6367 // If the LHS is an AND of a truncating cast, we can widen the
6368 // and/compare to be the input width without changing the value
6369 // produced, eliminating a cast.
6370 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6371 // We can do this transformation if either the AND constant does not
6372 // have its sign bit set or if it is an equality comparison.
6373 // Extending a relational comparison when we're checking the sign
6374 // bit would not work.
6375 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006376 (ICI.isEquality() ||
6377 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006378 uint32_t BitWidth =
6379 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6380 APInt NewCST = AndCST->getValue();
6381 NewCST.zext(BitWidth);
6382 APInt NewCI = RHSV;
6383 NewCI.zext(BitWidth);
6384 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006385 BinaryOperator::CreateAnd(Cast->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006386 ConstantInt::get(NewCST),LHSI->getName());
6387 InsertNewInstBefore(NewAnd, ICI);
6388 return new ICmpInst(ICI.getPredicate(), NewAnd,
6389 ConstantInt::get(NewCI));
6390 }
6391 }
6392
6393 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6394 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6395 // happens a LOT in code produced by the C front-end, for bitfield
6396 // access.
6397 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6398 if (Shift && !Shift->isShift())
6399 Shift = 0;
6400
6401 ConstantInt *ShAmt;
6402 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6403 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6404 const Type *AndTy = AndCST->getType(); // Type of the and.
6405
6406 // We can fold this as long as we can't shift unknown bits
6407 // into the mask. This can only happen with signed shift
6408 // rights, as they sign-extend.
6409 if (ShAmt) {
6410 bool CanFold = Shift->isLogicalShift();
6411 if (!CanFold) {
6412 // To test for the bad case of the signed shr, see if any
6413 // of the bits shifted in could be tested after the mask.
6414 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6415 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6416
6417 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6418 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6419 AndCST->getValue()) == 0)
6420 CanFold = true;
6421 }
6422
6423 if (CanFold) {
6424 Constant *NewCst;
6425 if (Shift->getOpcode() == Instruction::Shl)
6426 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6427 else
6428 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6429
6430 // Check to see if we are shifting out any of the bits being
6431 // compared.
6432 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6433 // If we shifted bits out, the fold is not going to work out.
6434 // As a special case, check to see if this means that the
6435 // result is always true or false now.
6436 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6437 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6438 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6439 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6440 } else {
6441 ICI.setOperand(1, NewCst);
6442 Constant *NewAndCST;
6443 if (Shift->getOpcode() == Instruction::Shl)
6444 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6445 else
6446 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6447 LHSI->setOperand(1, NewAndCST);
6448 LHSI->setOperand(0, Shift->getOperand(0));
6449 AddToWorkList(Shift); // Shift is dead.
6450 AddUsesToWorkList(ICI);
6451 return &ICI;
6452 }
6453 }
6454 }
6455
6456 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6457 // preferable because it allows the C<<Y expression to be hoisted out
6458 // of a loop if Y is invariant and X is not.
6459 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6460 ICI.isEquality() && !Shift->isArithmeticShift() &&
6461 isa<Instruction>(Shift->getOperand(0))) {
6462 // Compute C << Y.
6463 Value *NS;
6464 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006465 NS = BinaryOperator::CreateShl(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006466 Shift->getOperand(1), "tmp");
6467 } else {
6468 // Insert a logical shift.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006469 NS = BinaryOperator::CreateLShr(AndCST,
Chris Lattner01deb9d2007-04-03 17:43:25 +00006470 Shift->getOperand(1), "tmp");
6471 }
6472 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6473
6474 // Compute X & (C << Y).
6475 Instruction *NewAnd =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006476 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006477 InsertNewInstBefore(NewAnd, ICI);
6478
6479 ICI.setOperand(0, NewAnd);
6480 return &ICI;
6481 }
6482 }
6483 break;
6484
Chris Lattnera0141b92007-07-15 20:42:37 +00006485 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6486 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6487 if (!ShAmt) break;
6488
6489 uint32_t TypeBits = RHSV.getBitWidth();
6490
6491 // Check that the shift amount is in range. If not, don't perform
6492 // undefined shifts. When the shift is visited it will be
6493 // simplified.
6494 if (ShAmt->uge(TypeBits))
6495 break;
6496
6497 if (ICI.isEquality()) {
6498 // If we are comparing against bits always shifted out, the
6499 // comparison cannot succeed.
6500 Constant *Comp =
6501 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6502 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6503 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6504 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6505 return ReplaceInstUsesWith(ICI, Cst);
6506 }
6507
6508 if (LHSI->hasOneUse()) {
6509 // Otherwise strength reduce the shift into an and.
6510 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6511 Constant *Mask =
6512 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006513
Chris Lattnera0141b92007-07-15 20:42:37 +00006514 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006515 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006516 Mask, LHSI->getName()+".mask");
6517 Value *And = InsertNewInstBefore(AndI, ICI);
6518 return new ICmpInst(ICI.getPredicate(), And,
6519 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006520 }
6521 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006522
6523 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6524 bool TrueIfSigned = false;
6525 if (LHSI->hasOneUse() &&
6526 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6527 // (X << 31) <s 0 --> (X&1) != 0
6528 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6529 (TypeBits-ShAmt->getZExtValue()-1));
6530 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006531 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattnera0141b92007-07-15 20:42:37 +00006532 Mask, LHSI->getName()+".mask");
6533 Value *And = InsertNewInstBefore(AndI, ICI);
6534
6535 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6536 And, Constant::getNullValue(And->getType()));
6537 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006538 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006539 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006540
6541 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006542 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006543 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006544 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006545 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006546
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006547 // Check that the shift amount is in range. If not, don't perform
6548 // undefined shifts. When the shift is visited it will be
6549 // simplified.
6550 uint32_t TypeBits = RHSV.getBitWidth();
6551 if (ShAmt->uge(TypeBits))
6552 break;
6553
6554 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006555
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006556 // If we are comparing against bits always shifted out, the
6557 // comparison cannot succeed.
6558 APInt Comp = RHSV << ShAmtVal;
6559 if (LHSI->getOpcode() == Instruction::LShr)
6560 Comp = Comp.lshr(ShAmtVal);
6561 else
6562 Comp = Comp.ashr(ShAmtVal);
6563
6564 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6565 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6566 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6567 return ReplaceInstUsesWith(ICI, Cst);
6568 }
6569
6570 // Otherwise, check to see if the bits shifted out are known to be zero.
6571 // If so, we can compare against the unshifted value:
6572 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006573 if (LHSI->hasOneUse() &&
6574 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006575 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6576 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6577 ConstantExpr::getShl(RHS, ShAmt));
6578 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006579
Evan Chengf30752c2008-04-23 00:38:06 +00006580 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006581 // Otherwise strength reduce the shift into an and.
6582 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6583 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006584
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006585 Instruction *AndI =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006586 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006587 Mask, LHSI->getName()+".mask");
6588 Value *And = InsertNewInstBefore(AndI, ICI);
6589 return new ICmpInst(ICI.getPredicate(), And,
6590 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006591 }
6592 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006593 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006594
6595 case Instruction::SDiv:
6596 case Instruction::UDiv:
6597 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6598 // Fold this div into the comparison, producing a range check.
6599 // Determine, based on the divide type, what the range is being
6600 // checked. If there is an overflow on the low or high side, remember
6601 // it, otherwise compute the range [low, hi) bounding the new value.
6602 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006603 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6604 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6605 DivRHS))
6606 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006607 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006608
6609 case Instruction::Add:
6610 // Fold: icmp pred (add, X, C1), C2
6611
6612 if (!ICI.isEquality()) {
6613 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6614 if (!LHSC) break;
6615 const APInt &LHSV = LHSC->getValue();
6616
6617 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6618 .subtract(LHSV);
6619
6620 if (ICI.isSignedPredicate()) {
6621 if (CR.getLower().isSignBit()) {
6622 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6623 ConstantInt::get(CR.getUpper()));
6624 } else if (CR.getUpper().isSignBit()) {
6625 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6626 ConstantInt::get(CR.getLower()));
6627 }
6628 } else {
6629 if (CR.getLower().isMinValue()) {
6630 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6631 ConstantInt::get(CR.getUpper()));
6632 } else if (CR.getUpper().isMinValue()) {
6633 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6634 ConstantInt::get(CR.getLower()));
6635 }
6636 }
6637 }
6638 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006639 }
6640
6641 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6642 if (ICI.isEquality()) {
6643 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6644
6645 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6646 // the second operand is a constant, simplify a bit.
6647 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6648 switch (BO->getOpcode()) {
6649 case Instruction::SRem:
6650 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6651 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6652 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6653 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6654 Instruction *NewRem =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006655 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006656 BO->getName());
6657 InsertNewInstBefore(NewRem, ICI);
6658 return new ICmpInst(ICI.getPredicate(), NewRem,
6659 Constant::getNullValue(BO->getType()));
6660 }
6661 }
6662 break;
6663 case Instruction::Add:
6664 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6665 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6666 if (BO->hasOneUse())
6667 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6668 Subtract(RHS, BOp1C));
6669 } else if (RHSV == 0) {
6670 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6671 // efficiently invertible, or if the add has just this one use.
6672 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6673
6674 if (Value *NegVal = dyn_castNegVal(BOp1))
6675 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6676 else if (Value *NegVal = dyn_castNegVal(BOp0))
6677 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6678 else if (BO->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006679 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006680 InsertNewInstBefore(Neg, ICI);
6681 Neg->takeName(BO);
6682 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6683 }
6684 }
6685 break;
6686 case Instruction::Xor:
6687 // For the xor case, we can xor two constants together, eliminating
6688 // the explicit xor.
6689 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6690 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6691 ConstantExpr::getXor(RHS, BOC));
6692
6693 // FALLTHROUGH
6694 case Instruction::Sub:
6695 // Replace (([sub|xor] A, B) != 0) with (A != B)
6696 if (RHSV == 0)
6697 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6698 BO->getOperand(1));
6699 break;
6700
6701 case Instruction::Or:
6702 // If bits are being or'd in that are not present in the constant we
6703 // are comparing against, then the comparison could never succeed!
6704 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6705 Constant *NotCI = ConstantExpr::getNot(RHS);
6706 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6707 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6708 isICMP_NE));
6709 }
6710 break;
6711
6712 case Instruction::And:
6713 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6714 // If bits are being compared against that are and'd out, then the
6715 // comparison can never succeed!
6716 if ((RHSV & ~BOC->getValue()) != 0)
6717 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6718 isICMP_NE));
6719
6720 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6721 if (RHS == BOC && RHSV.isPowerOf2())
6722 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6723 ICmpInst::ICMP_NE, LHSI,
6724 Constant::getNullValue(RHS->getType()));
6725
6726 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6727 if (isSignBit(BOC)) {
6728 Value *X = BO->getOperand(0);
6729 Constant *Zero = Constant::getNullValue(X->getType());
6730 ICmpInst::Predicate pred = isICMP_NE ?
6731 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6732 return new ICmpInst(pred, X, Zero);
6733 }
6734
6735 // ((X & ~7) == 0) --> X < 8
6736 if (RHSV == 0 && isHighOnes(BOC)) {
6737 Value *X = BO->getOperand(0);
6738 Constant *NegX = ConstantExpr::getNeg(BOC);
6739 ICmpInst::Predicate pred = isICMP_NE ?
6740 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6741 return new ICmpInst(pred, X, NegX);
6742 }
6743 }
6744 default: break;
6745 }
6746 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6747 // Handle icmp {eq|ne} <intrinsic>, intcst.
6748 if (II->getIntrinsicID() == Intrinsic::bswap) {
6749 AddToWorkList(II);
6750 ICI.setOperand(0, II->getOperand(1));
6751 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6752 return &ICI;
6753 }
6754 }
6755 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00006756 // If the LHS is a cast from an integral value of the same size,
6757 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006758 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6759 Value *CastOp = Cast->getOperand(0);
6760 const Type *SrcTy = CastOp->getType();
6761 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6762 if (SrcTy->isInteger() &&
6763 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6764 // If this is an unsigned comparison, try to make the comparison use
6765 // smaller constant values.
6766 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6767 // X u< 128 => X s> -1
6768 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6769 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6770 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6771 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6772 // X u> 127 => X s< 0
6773 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6774 Constant::getNullValue(SrcTy));
6775 }
6776 }
6777 }
6778 }
6779 return 0;
6780}
6781
6782/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6783/// We only handle extending casts so far.
6784///
Reid Spencere4d87aa2006-12-23 06:05:41 +00006785Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6786 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00006787 Value *LHSCIOp = LHSCI->getOperand(0);
6788 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006789 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006790 Value *RHSCIOp;
6791
Chris Lattner8c756c12007-05-05 22:41:33 +00006792 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6793 // integer type is the same size as the pointer type.
6794 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6795 getTargetData().getPointerSizeInBits() ==
6796 cast<IntegerType>(DestTy)->getBitWidth()) {
6797 Value *RHSOp = 0;
6798 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006799 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006800 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6801 RHSOp = RHSC->getOperand(0);
6802 // If the pointer types don't match, insert a bitcast.
6803 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006804 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006805 }
6806
6807 if (RHSOp)
6808 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6809 }
6810
6811 // The code below only handles extension cast instructions, so far.
6812 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006813 if (LHSCI->getOpcode() != Instruction::ZExt &&
6814 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006815 return 0;
6816
Reid Spencere4d87aa2006-12-23 06:05:41 +00006817 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6818 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006819
Reid Spencere4d87aa2006-12-23 06:05:41 +00006820 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006821 // Not an extension from the same type?
6822 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006823 if (RHSCIOp->getType() != LHSCIOp->getType())
6824 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006825
Nick Lewycky4189a532008-01-28 03:48:02 +00006826 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006827 // and the other is a zext), then we can't handle this.
6828 if (CI->getOpcode() != LHSCI->getOpcode())
6829 return 0;
6830
Nick Lewycky4189a532008-01-28 03:48:02 +00006831 // Deal with equality cases early.
6832 if (ICI.isEquality())
6833 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6834
6835 // A signed comparison of sign extended values simplifies into a
6836 // signed comparison.
6837 if (isSignedCmp && isSignedExt)
6838 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6839
6840 // The other three cases all fold into an unsigned comparison.
6841 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006842 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006843
Reid Spencere4d87aa2006-12-23 06:05:41 +00006844 // If we aren't dealing with a constant on the RHS, exit early
6845 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6846 if (!CI)
6847 return 0;
6848
6849 // Compute the constant that would happen if we truncated to SrcTy then
6850 // reextended to DestTy.
6851 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6852 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6853
6854 // If the re-extended constant didn't change...
6855 if (Res2 == CI) {
6856 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6857 // For example, we might have:
6858 // %A = sext short %X to uint
6859 // %B = icmp ugt uint %A, 1330
6860 // It is incorrect to transform this into
6861 // %B = icmp ugt short %X, 1330
6862 // because %A may have negative value.
6863 //
6864 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6865 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006866 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006867 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6868 else
6869 return 0;
6870 }
6871
6872 // The re-extended constant changed so the constant cannot be represented
6873 // in the shorter type. Consequently, we cannot emit a simple comparison.
6874
6875 // First, handle some easy cases. We know the result cannot be equal at this
6876 // point so handle the ICI.isEquality() cases
6877 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006878 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006879 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006880 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006881
6882 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6883 // should have been folded away previously and not enter in here.
6884 Value *Result;
6885 if (isSignedCmp) {
6886 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006887 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006888 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006889 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006890 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006891 } else {
6892 // We're performing an unsigned comparison.
6893 if (isSignedExt) {
6894 // We're performing an unsigned comp with a sign extended value.
6895 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006896 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006897 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6898 NegOne, ICI.getName()), ICI);
6899 } else {
6900 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006901 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006902 }
6903 }
6904
6905 // Finally, return the value computed.
6906 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6907 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6908 return ReplaceInstUsesWith(ICI, Result);
6909 } else {
6910 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6911 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6912 "ICmp should be folded!");
6913 if (Constant *CI = dyn_cast<Constant>(Result))
6914 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6915 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006916 return BinaryOperator::CreateNot(Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006917 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006918}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006919
Reid Spencer832254e2007-02-02 02:16:23 +00006920Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6921 return commonShiftTransforms(I);
6922}
6923
6924Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6925 return commonShiftTransforms(I);
6926}
6927
6928Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006929 if (Instruction *R = commonShiftTransforms(I))
6930 return R;
6931
6932 Value *Op0 = I.getOperand(0);
6933
6934 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6935 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6936 if (CSI->isAllOnesValue())
6937 return ReplaceInstUsesWith(I, CSI);
6938
6939 // See if we can turn a signed shr into an unsigned shr.
6940 if (MaskedValueIsZero(Op0,
6941 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006942 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattner348f6652007-12-06 01:59:46 +00006943
6944 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006945}
6946
6947Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6948 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006949 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006950
6951 // shl X, 0 == X and shr X, 0 == X
6952 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006953 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006954 Op0 == Constant::getNullValue(Op0->getType()))
6955 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006956
Reid Spencere4d87aa2006-12-23 06:05:41 +00006957 if (isa<UndefValue>(Op0)) {
6958 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006959 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006960 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006961 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6962 }
6963 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006964 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6965 return ReplaceInstUsesWith(I, Op0);
6966 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006967 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006968 }
6969
Chris Lattner2eefe512004-04-09 19:05:30 +00006970 // Try to fold constant and into select arguments.
6971 if (isa<Constant>(Op0))
6972 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006973 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006974 return R;
6975
Reid Spencerb83eb642006-10-20 07:07:24 +00006976 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006977 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6978 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006979 return 0;
6980}
6981
Reid Spencerb83eb642006-10-20 07:07:24 +00006982Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006983 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006984 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006985
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006986 // See if we can simplify any instructions used by the instruction whose sole
6987 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006988 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6989 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6990 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006991 KnownZero, KnownOne))
6992 return &I;
6993
Chris Lattner4d5542c2006-01-06 07:12:35 +00006994 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6995 // of a signed value.
6996 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006997 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006998 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006999 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7000 else {
Chris Lattner0737c242007-02-02 05:29:55 +00007001 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007002 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007003 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007004 }
7005
7006 // ((X*C1) << C2) == (X * (C1 << C2))
7007 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7008 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7009 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007010 return BinaryOperator::CreateMul(BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007011 ConstantExpr::getShl(BOOp, Op1));
7012
7013 // Try to fold constant and into select arguments.
7014 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7015 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7016 return R;
7017 if (isa<PHINode>(Op0))
7018 if (Instruction *NV = FoldOpIntoPhi(I))
7019 return NV;
7020
Chris Lattner8999dd32007-12-22 09:07:47 +00007021 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7022 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7023 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7024 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7025 // place. Don't try to do this transformation in this case. Also, we
7026 // require that the input operand is a shift-by-constant so that we have
7027 // confidence that the shifts will get folded together. We could do this
7028 // xform in more cases, but it is unlikely to be profitable.
7029 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7030 isa<ConstantInt>(TrOp->getOperand(1))) {
7031 // Okay, we'll do this xform. Make the shift of shift.
7032 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007033 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattner8999dd32007-12-22 09:07:47 +00007034 I.getName());
7035 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7036
7037 // For logical shifts, the truncation has the effect of making the high
7038 // part of the register be zeros. Emulate this by inserting an AND to
7039 // clear the top bits as needed. This 'and' will usually be zapped by
7040 // other xforms later if dead.
7041 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7042 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7043 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7044
7045 // The mask we constructed says what the trunc would do if occurring
7046 // between the shifts. We want to know the effect *after* the second
7047 // shift. We know that it is a logical shift by a constant, so adjust the
7048 // mask as appropriate.
7049 if (I.getOpcode() == Instruction::Shl)
7050 MaskV <<= Op1->getZExtValue();
7051 else {
7052 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7053 MaskV = MaskV.lshr(Op1->getZExtValue());
7054 }
7055
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007056 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattner8999dd32007-12-22 09:07:47 +00007057 TI->getName());
7058 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7059
7060 // Return the value truncated to the interesting size.
7061 return new TruncInst(And, I.getType());
7062 }
7063 }
7064
Chris Lattner4d5542c2006-01-06 07:12:35 +00007065 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007066 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7067 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7068 Value *V1, *V2;
7069 ConstantInt *CC;
7070 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007071 default: break;
7072 case Instruction::Add:
7073 case Instruction::And:
7074 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007075 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007076 // These operators commute.
7077 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007078 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7079 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007080 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007081 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007082 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007083 Op0BO->getName());
7084 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007085 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007086 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007087 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007088 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007089 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007090 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007091 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007092 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007093
Chris Lattner150f12a2005-09-18 06:30:59 +00007094 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007095 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007096 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007097 match(Op0BOOp1,
7098 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00007099 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7100 V2 == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007101 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007102 Op0BO->getOperand(0), Op1,
7103 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007104 InsertNewInstBefore(YS, I); // (Y << C)
7105 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007106 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007107 V1->getName()+".mask");
7108 InsertNewInstBefore(XM, I); // X & (CC << C)
7109
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007110 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007111 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007112 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007113
Reid Spencera07cb7d2007-02-02 14:41:37 +00007114 // FALL THROUGH.
7115 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007116 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007117 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7118 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007119 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007120 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007121 Op0BO->getOperand(1), Op1,
7122 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007123 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007124 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007125 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007126 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007127 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007128 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007129 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Zhou Sheng90b96812007-03-30 05:45:18 +00007130 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007131 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007132
Chris Lattner13d4ab42006-05-31 21:14:00 +00007133 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007134 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7135 match(Op0BO->getOperand(0),
7136 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00007137 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007138 cast<BinaryOperator>(Op0BO->getOperand(0))
7139 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007140 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007141 Op0BO->getOperand(1), Op1,
7142 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007143 InsertNewInstBefore(YS, I); // (Y << C)
7144 Instruction *XM =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007145 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007146 V1->getName()+".mask");
7147 InsertNewInstBefore(XM, I); // X & (CC << C)
7148
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007149 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007150 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007151
Chris Lattner11021cb2005-09-18 05:12:10 +00007152 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007153 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007154 }
7155
7156
7157 // If the operand is an bitwise operator with a constant RHS, and the
7158 // shift is the only use, we can pull it out of the shift.
7159 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7160 bool isValid = true; // Valid only for And, Or, Xor
7161 bool highBitSet = false; // Transform if high bit of constant set?
7162
7163 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007164 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007165 case Instruction::Add:
7166 isValid = isLeftShift;
7167 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007168 case Instruction::Or:
7169 case Instruction::Xor:
7170 highBitSet = false;
7171 break;
7172 case Instruction::And:
7173 highBitSet = true;
7174 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007175 }
7176
7177 // If this is a signed shift right, and the high bit is modified
7178 // by the logical operation, do not perform the transformation.
7179 // The highBitSet boolean indicates the value of the high bit of
7180 // the constant which would cause it to be modified for this
7181 // operation.
7182 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007183 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007184 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007185
7186 if (isValid) {
7187 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7188
7189 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007190 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007191 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007192 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007193
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007194 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007195 NewRHS);
7196 }
7197 }
7198 }
7199 }
7200
Chris Lattnerad0124c2006-01-06 07:52:12 +00007201 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007202 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7203 if (ShiftOp && !ShiftOp->isShift())
7204 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007205
Reid Spencerb83eb642006-10-20 07:07:24 +00007206 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007207 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007208 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7209 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007210 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7211 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7212 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007213
Zhou Sheng4351c642007-04-02 08:20:41 +00007214 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00007215 if (AmtSum > TypeBits)
7216 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007217
7218 const IntegerType *Ty = cast<IntegerType>(I.getType());
7219
7220 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007221 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007222 return BinaryOperator::Create(I.getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007223 ConstantInt::get(Ty, AmtSum));
7224 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7225 I.getOpcode() == Instruction::AShr) {
7226 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007227 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007228 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7229 I.getOpcode() == Instruction::LShr) {
7230 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7231 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007232 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007233 InsertNewInstBefore(Shift, I);
7234
Zhou Shenge9e03f62007-03-28 15:02:20 +00007235 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007236 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007237 }
7238
Chris Lattnerb87056f2007-02-05 00:57:54 +00007239 // Okay, if we get here, one shift must be left, and the other shift must be
7240 // right. See if the amounts are equal.
7241 if (ShiftAmt1 == ShiftAmt2) {
7242 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7243 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007244 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007245 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007246 }
7247 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7248 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007249 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007250 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007251 }
7252 // We can simplify ((X << C) >>s C) into a trunc + sext.
7253 // NOTE: we could do this for any C, but that would make 'unusual' integer
7254 // types. For now, just stick to ones well-supported by the code
7255 // generators.
7256 const Type *SExtType = 0;
7257 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007258 case 1 :
7259 case 8 :
7260 case 16 :
7261 case 32 :
7262 case 64 :
7263 case 128:
7264 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7265 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007266 default: break;
7267 }
7268 if (SExtType) {
7269 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7270 InsertNewInstBefore(NewTrunc, I);
7271 return new SExtInst(NewTrunc, Ty);
7272 }
7273 // Otherwise, we can't handle it yet.
7274 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007275 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007276
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007277 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007278 if (I.getOpcode() == Instruction::Shl) {
7279 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7280 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007281 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007282 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007283 InsertNewInstBefore(Shift, I);
7284
Reid Spencer55702aa2007-03-25 21:11:44 +00007285 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007286 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007287 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007288
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007289 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007290 if (I.getOpcode() == Instruction::LShr) {
7291 assert(ShiftOp->getOpcode() == Instruction::Shl);
7292 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007293 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007294 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007295
Reid Spencerd5e30f02007-03-26 17:18:58 +00007296 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007297 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007298 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007299
7300 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7301 } else {
7302 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007303 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007304
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007305 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007306 if (I.getOpcode() == Instruction::Shl) {
7307 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7308 ShiftOp->getOpcode() == Instruction::AShr);
7309 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007310 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Chris Lattnerb87056f2007-02-05 00:57:54 +00007311 ConstantInt::get(Ty, ShiftDiff));
7312 InsertNewInstBefore(Shift, I);
7313
Reid Spencer55702aa2007-03-25 21:11:44 +00007314 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007315 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007316 }
7317
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007318 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007319 if (I.getOpcode() == Instruction::LShr) {
7320 assert(ShiftOp->getOpcode() == Instruction::Shl);
7321 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007322 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007323 InsertNewInstBefore(Shift, I);
7324
Reid Spencer68d27cf2007-03-26 23:45:51 +00007325 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007326 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007327 }
7328
7329 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007330 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007331 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007332 return 0;
7333}
7334
Chris Lattnera1be5662002-05-02 17:06:02 +00007335
Chris Lattnercfd65102005-10-29 04:36:15 +00007336/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7337/// expression. If so, decompose it, returning some value X, such that Val is
7338/// X*Scale+Offset.
7339///
7340static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00007341 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007342 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007343 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007344 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007345 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00007346 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007347 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7349 if (I->getOpcode() == Instruction::Shl) {
7350 // This is a value scaled by '1 << the shift amt'.
7351 Scale = 1U << RHS->getZExtValue();
7352 Offset = 0;
7353 return I->getOperand(0);
7354 } else if (I->getOpcode() == Instruction::Mul) {
7355 // This value is scaled by 'RHS'.
7356 Scale = RHS->getZExtValue();
7357 Offset = 0;
7358 return I->getOperand(0);
7359 } else if (I->getOpcode() == Instruction::Add) {
7360 // We have X+C. Check to see if we really have (X*C2)+C1,
7361 // where C1 is divisible by C2.
7362 unsigned SubScale;
7363 Value *SubVal =
7364 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7365 Offset += RHS->getZExtValue();
7366 Scale = SubScale;
7367 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007368 }
7369 }
7370 }
7371
7372 // Otherwise, we can't look past this.
7373 Scale = 1;
7374 Offset = 0;
7375 return Val;
7376}
7377
7378
Chris Lattnerb3f83972005-10-24 06:03:58 +00007379/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7380/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007381Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007382 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007383 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007384
Chris Lattnerb53c2382005-10-24 06:22:12 +00007385 // Remove any uses of AI that are dead.
7386 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007387
Chris Lattnerb53c2382005-10-24 06:22:12 +00007388 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7389 Instruction *User = cast<Instruction>(*UI++);
7390 if (isInstructionTriviallyDead(User)) {
7391 while (UI != E && *UI == User)
7392 ++UI; // If this instruction uses AI more than once, don't break UI.
7393
Chris Lattnerb53c2382005-10-24 06:22:12 +00007394 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00007395 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007396 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007397 }
7398 }
7399
Chris Lattnerb3f83972005-10-24 06:03:58 +00007400 // Get the type really allocated and the type casted to.
7401 const Type *AllocElTy = AI.getAllocatedType();
7402 const Type *CastElTy = PTy->getElementType();
7403 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007404
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007405 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7406 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007407 if (CastElTyAlign < AllocElTyAlign) return 0;
7408
Chris Lattner39387a52005-10-24 06:35:18 +00007409 // If the allocation has multiple uses, only promote it if we are strictly
7410 // increasing the alignment of the resultant allocation. If we keep it the
7411 // same, we open the door to infinite loops of various kinds.
7412 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7413
Duncan Sands514ab342007-11-01 20:53:16 +00007414 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7415 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007416 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007417
Chris Lattner455fcc82005-10-29 03:19:53 +00007418 // See if we can satisfy the modulus by pulling a scale out of the array
7419 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007420 unsigned ArraySizeScale;
7421 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007422 Value *NumElements = // See if the array size is a decomposable linear expr.
7423 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7424
Chris Lattner455fcc82005-10-29 03:19:53 +00007425 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7426 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007427 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7428 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007429
Chris Lattner455fcc82005-10-29 03:19:53 +00007430 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7431 Value *Amt = 0;
7432 if (Scale == 1) {
7433 Amt = NumElements;
7434 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007435 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00007436 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7437 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00007438 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007439 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00007440 else if (Scale != 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007441 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007442 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007443 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007444 }
7445
Jeff Cohen86796be2007-04-04 16:58:57 +00007446 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7447 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007448 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007449 Amt = InsertNewInstBefore(Tmp, AI);
7450 }
7451
Chris Lattnerb3f83972005-10-24 06:03:58 +00007452 AllocationInst *New;
7453 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00007454 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007455 else
Chris Lattner6934a042007-02-11 01:23:03 +00007456 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007457 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007458 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007459
7460 // If the allocation has multiple uses, insert a cast and change all things
7461 // that used it to use the new cast. This will also hack on CI, but it will
7462 // die soon.
7463 if (!AI.hasOneUse()) {
7464 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007465 // New is the allocation instruction, pointer typed. AI is the original
7466 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7467 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007468 InsertNewInstBefore(NewCast, AI);
7469 AI.replaceAllUsesWith(NewCast);
7470 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007471 return ReplaceInstUsesWith(CI, New);
7472}
7473
Chris Lattner70074e02006-05-13 02:06:03 +00007474/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007475/// and return it as type Ty without inserting any new casts and without
7476/// changing the computed value. This is used by code that tries to decide
7477/// whether promoting or shrinking integer operations to wider or smaller types
7478/// will allow us to eliminate a truncate or extend.
7479///
7480/// This is a truncation operation if Ty is smaller than V->getType(), or an
7481/// extension operation if Ty is larger.
Dan Gohmaneee962e2008-04-10 18:43:06 +00007482bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7483 unsigned CastOpc,
7484 int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007485 // We can always evaluate constants in another type.
7486 if (isa<ConstantInt>(V))
7487 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007488
7489 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007490 if (!I) return false;
7491
7492 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00007493
Chris Lattner951626b2007-08-02 06:11:14 +00007494 // If this is an extension or truncate, we can often eliminate it.
7495 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7496 // If this is a cast from the destination type, we can trivially eliminate
7497 // it, and this will remove a cast overall.
7498 if (I->getOperand(0)->getType() == Ty) {
7499 // If the first operand is itself a cast, and is eliminable, do not count
7500 // this as an eliminable cast. We would prefer to eliminate those two
7501 // casts first.
7502 if (!isa<CastInst>(I->getOperand(0)))
7503 ++NumCastsRemoved;
7504 return true;
7505 }
7506 }
7507
7508 // We can't extend or shrink something that has multiple uses: doing so would
7509 // require duplicating the instruction in general, which isn't profitable.
7510 if (!I->hasOneUse()) return false;
7511
Chris Lattner70074e02006-05-13 02:06:03 +00007512 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007513 case Instruction::Add:
7514 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00007515 case Instruction::And:
7516 case Instruction::Or:
7517 case Instruction::Xor:
7518 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007519 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7520 NumCastsRemoved) &&
7521 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7522 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007523
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007524 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007525 // A multiply can be truncated by truncating its operands.
7526 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7527 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7528 NumCastsRemoved) &&
7529 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7530 NumCastsRemoved);
7531
Chris Lattner46b96052006-11-29 07:18:39 +00007532 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007533 // If we are truncating the result of this SHL, and if it's a shift of a
7534 // constant amount, we can always perform a SHL in a smaller type.
7535 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007536 uint32_t BitWidth = Ty->getBitWidth();
7537 if (BitWidth < OrigTy->getBitWidth() &&
7538 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007539 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7540 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007541 }
7542 break;
7543 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007544 // If this is a truncate of a logical shr, we can truncate it to a smaller
7545 // lshr iff we know that the bits we would otherwise be shifting in are
7546 // already zeros.
7547 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007548 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7549 uint32_t BitWidth = Ty->getBitWidth();
7550 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007551 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007552 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7553 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007554 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7555 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007556 }
7557 }
Chris Lattner46b96052006-11-29 07:18:39 +00007558 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007559 case Instruction::ZExt:
7560 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007561 case Instruction::Trunc:
7562 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007563 // can safely replace it. Note that replacing it does not reduce the number
7564 // of casts in the input.
7565 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00007566 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00007567
Reid Spencer3da59db2006-11-27 01:05:10 +00007568 break;
7569 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007570 // TODO: Can handle more cases here.
7571 break;
7572 }
7573
7574 return false;
7575}
7576
7577/// EvaluateInDifferentType - Given an expression that
7578/// CanEvaluateInDifferentType returns true for, actually insert the code to
7579/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007580Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007581 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007582 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00007583 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007584
7585 // Otherwise, it must be an instruction.
7586 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007587 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00007588 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007589 case Instruction::Add:
7590 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007591 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007592 case Instruction::And:
7593 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007594 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007595 case Instruction::AShr:
7596 case Instruction::LShr:
7597 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007598 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007599 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007600 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Chris Lattnerc739cd62007-03-03 05:27:34 +00007601 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00007602 break;
7603 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007604 case Instruction::Trunc:
7605 case Instruction::ZExt:
7606 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007607 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007608 // just return the source. There's no need to insert it because it is not
7609 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007610 if (I->getOperand(0)->getType() == Ty)
7611 return I->getOperand(0);
7612
Chris Lattner951626b2007-08-02 06:11:14 +00007613 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007614 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner951626b2007-08-02 06:11:14 +00007615 Ty, I->getName());
7616 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007617 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007618 // TODO: Can handle more cases here.
7619 assert(0 && "Unreachable!");
7620 break;
7621 }
7622
7623 return InsertNewInstBefore(Res, *I);
7624}
7625
Reid Spencer3da59db2006-11-27 01:05:10 +00007626/// @brief Implement the transforms common to all CastInst visitors.
7627Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007628 Value *Src = CI.getOperand(0);
7629
Dan Gohman23d9d272007-05-11 21:10:54 +00007630 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007631 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007632 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007633 if (Instruction::CastOps opc =
7634 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7635 // The first cast (CSrc) is eliminable so we need to fix up or replace
7636 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007637 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007638 }
7639 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007640
Reid Spencer3da59db2006-11-27 01:05:10 +00007641 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007642 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7643 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7644 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007645
7646 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007647 if (isa<PHINode>(Src))
7648 if (Instruction *NV = FoldOpIntoPhi(CI))
7649 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007650
Reid Spencer3da59db2006-11-27 01:05:10 +00007651 return 0;
7652}
7653
Chris Lattnerd3e28342007-04-27 17:44:50 +00007654/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7655Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7656 Value *Src = CI.getOperand(0);
7657
Chris Lattnerd3e28342007-04-27 17:44:50 +00007658 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00007659 // If casting the result of a getelementptr instruction with no offset, turn
7660 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00007661 if (GEP->hasAllZeroIndices()) {
7662 // Changing the cast operand is usually not a good idea but it is safe
7663 // here because the pointer operand is being replaced with another
7664 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00007665 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00007666 CI.setOperand(0, GEP->getOperand(0));
7667 return &CI;
7668 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007669
7670 // If the GEP has a single use, and the base pointer is a bitcast, and the
7671 // GEP computes a constant offset, see if we can convert these three
7672 // instructions into fewer. This typically happens with unions and other
7673 // non-type-safe code.
7674 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7675 if (GEP->hasAllConstantIndices()) {
7676 // We are guaranteed to get a constant from EmitGEPOffset.
7677 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7678 int64_t Offset = OffsetV->getSExtValue();
7679
7680 // Get the base pointer input of the bitcast, and the type it points to.
7681 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7682 const Type *GEPIdxTy =
7683 cast<PointerType>(OrigBase->getType())->getElementType();
7684 if (GEPIdxTy->isSized()) {
7685 SmallVector<Value*, 8> NewIndices;
7686
Chris Lattnerc42e2262007-05-05 01:59:31 +00007687 // Start with the index over the outer type. Note that the type size
7688 // might be zero (even if the offset isn't zero) if the indexed type
7689 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00007690 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00007691 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00007692 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00007693 FirstIdx = Offset/TySize;
7694 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00007695
Chris Lattnerc42e2262007-05-05 01:59:31 +00007696 // Handle silly modulus not returning values values [0..TySize).
7697 if (Offset < 0) {
7698 --FirstIdx;
7699 Offset += TySize;
7700 assert(Offset >= 0);
7701 }
Chris Lattnerd717c182007-05-05 22:32:24 +00007702 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00007703 }
7704
7705 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00007706
7707 // Index into the types. If we fail, set OrigBase to null.
7708 while (Offset) {
7709 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7710 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00007711 if (Offset < (int64_t)SL->getSizeInBytes()) {
7712 unsigned Elt = SL->getElementContainingOffset(Offset);
7713 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00007714
Chris Lattner6b6aef82007-05-15 00:16:00 +00007715 Offset -= SL->getElementOffset(Elt);
7716 GEPIdxTy = STy->getElementType(Elt);
7717 } else {
7718 // Otherwise, we can't index into this, bail out.
7719 Offset = 0;
7720 OrigBase = 0;
7721 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007722 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7723 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00007724 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00007725 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7726 Offset %= EltSize;
7727 } else {
7728 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7729 }
Chris Lattner9bc14642007-04-28 00:57:34 +00007730 GEPIdxTy = STy->getElementType();
7731 } else {
7732 // Otherwise, we can't index into this, bail out.
7733 Offset = 0;
7734 OrigBase = 0;
7735 }
7736 }
7737 if (OrigBase) {
7738 // If we were able to index down into an element, create the GEP
7739 // and bitcast the result. This eliminates one bitcast, potentially
7740 // two.
Gabor Greif051a9502008-04-06 20:25:17 +00007741 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7742 NewIndices.begin(),
7743 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00007744 InsertNewInstBefore(NGEP, CI);
7745 NGEP->takeName(GEP);
7746
Chris Lattner9bc14642007-04-28 00:57:34 +00007747 if (isa<BitCastInst>(CI))
7748 return new BitCastInst(NGEP, CI.getType());
7749 assert(isa<PtrToIntInst>(CI));
7750 return new PtrToIntInst(NGEP, CI.getType());
7751 }
7752 }
7753 }
7754 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00007755 }
7756
7757 return commonCastTransforms(CI);
7758}
7759
7760
7761
Chris Lattnerc739cd62007-03-03 05:27:34 +00007762/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7763/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00007764/// cases.
7765/// @brief Implement the transforms common to CastInst with integer operands
7766Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7767 if (Instruction *Result = commonCastTransforms(CI))
7768 return Result;
7769
7770 Value *Src = CI.getOperand(0);
7771 const Type *SrcTy = Src->getType();
7772 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007773 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7774 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007775
Reid Spencer3da59db2006-11-27 01:05:10 +00007776 // See if we can simplify any instructions used by the LHS whose sole
7777 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00007778 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7779 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00007780 KnownZero, KnownOne))
7781 return &CI;
7782
7783 // If the source isn't an instruction or has more than one use then we
7784 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007785 Instruction *SrcI = dyn_cast<Instruction>(Src);
7786 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00007787 return 0;
7788
Chris Lattnerc739cd62007-03-03 05:27:34 +00007789 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007790 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007791 if (!isa<BitCastInst>(CI) &&
7792 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007793 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007794 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007795 // eliminates the cast, so it is always a win. If this is a zero-extension,
7796 // we need to do an AND to maintain the clear top-part of the computation,
7797 // so we require that the input have eliminated at least one cast. If this
7798 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007799 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007800 bool DoXForm;
7801 switch (CI.getOpcode()) {
7802 default:
7803 // All the others use floating point so we shouldn't actually
7804 // get here because of the check above.
7805 assert(0 && "Unknown cast type");
7806 case Instruction::Trunc:
7807 DoXForm = true;
7808 break;
7809 case Instruction::ZExt:
7810 DoXForm = NumCastsRemoved >= 1;
7811 break;
7812 case Instruction::SExt:
7813 DoXForm = NumCastsRemoved >= 2;
7814 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007815 }
7816
7817 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007818 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7819 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007820 assert(Res->getType() == DestTy);
7821 switch (CI.getOpcode()) {
7822 default: assert(0 && "Unknown cast type!");
7823 case Instruction::Trunc:
7824 case Instruction::BitCast:
7825 // Just replace this cast with the result.
7826 return ReplaceInstUsesWith(CI, Res);
7827 case Instruction::ZExt: {
7828 // We need to emit an AND to clear the high bits.
7829 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007830 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7831 SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007832 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00007833 }
7834 case Instruction::SExt:
7835 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007836 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007837 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7838 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007839 }
7840 }
7841 }
7842
7843 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7844 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7845
7846 switch (SrcI->getOpcode()) {
7847 case Instruction::Add:
7848 case Instruction::Mul:
7849 case Instruction::And:
7850 case Instruction::Or:
7851 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007852 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007853 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7854 // Don't insert two casts if they cannot be eliminated. We allow
7855 // two casts to be inserted if the sizes are the same. This could
7856 // only be converting signedness, which is a noop.
7857 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007858 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7859 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007860 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007861 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7862 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007863 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00007864 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007865 }
7866 }
7867
7868 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7869 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7870 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007871 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007872 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007873 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007874 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00007875 }
7876 break;
7877 case Instruction::SDiv:
7878 case Instruction::UDiv:
7879 case Instruction::SRem:
7880 case Instruction::URem:
7881 // If we are just changing the sign, rewrite.
7882 if (DestBitSize == SrcBitSize) {
7883 // Don't insert two casts if they cannot be eliminated. We allow
7884 // two casts to be inserted if the sizes are the same. This could
7885 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007886 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7887 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007888 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7889 Op0, DestTy, SrcI);
7890 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7891 Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007892 return BinaryOperator::Create(
Reid Spencer3da59db2006-11-27 01:05:10 +00007893 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7894 }
7895 }
7896 break;
7897
7898 case Instruction::Shl:
7899 // Allow changing the sign of the source operand. Do not allow
7900 // changing the size of the shift, UNLESS the shift amount is a
7901 // constant. We must not change variable sized shifts to a smaller
7902 // size, because it is undefined to shift more bits out than exist
7903 // in the value.
7904 if (DestBitSize == SrcBitSize ||
7905 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007906 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7907 Instruction::BitCast : Instruction::Trunc);
7908 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007909 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007910 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007911 }
7912 break;
7913 case Instruction::AShr:
7914 // If this is a signed shr, and if all bits shifted in are about to be
7915 // truncated off, turn it into an unsigned shr to allow greater
7916 // simplifications.
7917 if (DestBitSize < SrcBitSize &&
7918 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007919 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007920 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7921 // Insert the new logical shift right.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007922 return BinaryOperator::CreateLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007923 }
7924 }
7925 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007926 }
7927 return 0;
7928}
7929
Chris Lattner8a9f5712007-04-11 06:57:46 +00007930Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007931 if (Instruction *Result = commonIntCastTransforms(CI))
7932 return Result;
7933
7934 Value *Src = CI.getOperand(0);
7935 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007936 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7937 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007938
7939 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7940 switch (SrcI->getOpcode()) {
7941 default: break;
7942 case Instruction::LShr:
7943 // We can shrink lshr to something smaller if we know the bits shifted in
7944 // are already zeros.
7945 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007946 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007947
7948 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007949 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007950 Value* SrcIOp0 = SrcI->getOperand(0);
7951 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007952 if (ShAmt >= DestBitWidth) // All zeros.
7953 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7954
7955 // Okay, we can shrink this. Truncate the input, then return a new
7956 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007957 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7958 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7959 Ty, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007960 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007961 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007962 } else { // This is a variable shr.
7963
7964 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7965 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7966 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007967 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007968 Value *One = ConstantInt::get(SrcI->getType(), 1);
7969
Reid Spencer832254e2007-02-02 02:16:23 +00007970 Value *V = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007971 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007972 "tmp"), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007973 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007974 SrcI->getOperand(0),
7975 "tmp"), CI);
7976 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007977 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007978 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007979 }
7980 break;
7981 }
7982 }
7983
7984 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007985}
7986
Evan Chengb98a10e2008-03-24 00:21:34 +00007987/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7988/// in order to eliminate the icmp.
7989Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7990 bool DoXform) {
7991 // If we are just checking for a icmp eq of a single bit and zext'ing it
7992 // to an integer, then shift the bit to the appropriate place and then
7993 // cast to integer to avoid the comparison.
7994 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7995 const APInt &Op1CV = Op1C->getValue();
7996
7997 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7998 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7999 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8000 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8001 if (!DoXform) return ICI;
8002
8003 Value *In = ICI->getOperand(0);
8004 Value *Sh = ConstantInt::get(In->getType(),
8005 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008006 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008007 In->getName()+".lobit"),
8008 CI);
8009 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008010 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008011 false/*ZExt*/, "tmp", &CI);
8012
8013 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8014 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008015 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008016 In->getName()+".not"),
8017 CI);
8018 }
8019
8020 return ReplaceInstUsesWith(CI, In);
8021 }
8022
8023
8024
8025 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8026 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8027 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8028 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8029 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8030 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8031 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8032 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8033 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8034 // This only works for EQ and NE
8035 ICI->isEquality()) {
8036 // If Op1C some other power of two, convert:
8037 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8038 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8039 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8040 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8041
8042 APInt KnownZeroMask(~KnownZero);
8043 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8044 if (!DoXform) return ICI;
8045
8046 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8047 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8048 // (X&4) == 2 --> false
8049 // (X&4) != 2 --> true
8050 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8051 Res = ConstantExpr::getZExt(Res, CI.getType());
8052 return ReplaceInstUsesWith(CI, Res);
8053 }
8054
8055 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8056 Value *In = ICI->getOperand(0);
8057 if (ShiftAmt) {
8058 // Perform a logical shr by shiftamt.
8059 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008060 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chengb98a10e2008-03-24 00:21:34 +00008061 ConstantInt::get(In->getType(), ShiftAmt),
8062 In->getName()+".lobit"), CI);
8063 }
8064
8065 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8066 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008067 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008068 InsertNewInstBefore(cast<Instruction>(In), CI);
8069 }
8070
8071 if (CI.getType() == In->getType())
8072 return ReplaceInstUsesWith(CI, In);
8073 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008074 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008075 }
8076 }
8077 }
8078
8079 return 0;
8080}
8081
Chris Lattner8a9f5712007-04-11 06:57:46 +00008082Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008083 // If one of the common conversion will work ..
8084 if (Instruction *Result = commonIntCastTransforms(CI))
8085 return Result;
8086
8087 Value *Src = CI.getOperand(0);
8088
8089 // If this is a cast of a cast
8090 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008091 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8092 // types and if the sizes are just right we can convert this into a logical
8093 // 'and' which will be much cheaper than the pair of casts.
8094 if (isa<TruncInst>(CSrc)) {
8095 // Get the sizes of the types involved
8096 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008097 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8098 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8099 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008100 // If we're actually extending zero bits and the trunc is a no-op
8101 if (MidSize < DstSize && SrcSize == DstSize) {
8102 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00008103 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00008104 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00008105 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008106 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Reid Spencer3da59db2006-11-27 01:05:10 +00008107 // Unfortunately, if the type changed, we need to cast it back.
8108 if (And->getType() != CI.getType()) {
8109 And->setName(CSrc->getName()+".mask");
8110 InsertNewInstBefore(And, CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008111 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00008112 }
8113 return And;
8114 }
8115 }
8116 }
8117
Evan Chengb98a10e2008-03-24 00:21:34 +00008118 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8119 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008120
Evan Chengb98a10e2008-03-24 00:21:34 +00008121 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8122 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8123 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8124 // of the (zext icmp) will be transformed.
8125 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8126 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8127 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8128 (transformZExtICmp(LHS, CI, false) ||
8129 transformZExtICmp(RHS, CI, false))) {
8130 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8131 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008132 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008133 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008134 }
8135
Reid Spencer3da59db2006-11-27 01:05:10 +00008136 return 0;
8137}
8138
Chris Lattner8a9f5712007-04-11 06:57:46 +00008139Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008140 if (Instruction *I = commonIntCastTransforms(CI))
8141 return I;
8142
Chris Lattner8a9f5712007-04-11 06:57:46 +00008143 Value *Src = CI.getOperand(0);
8144
8145 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8146 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8147 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8148 // If we are just checking for a icmp eq of a single bit and zext'ing it
8149 // to an integer, then shift the bit to the appropriate place and then
8150 // cast to integer to avoid the comparison.
8151 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8152 const APInt &Op1CV = Op1C->getValue();
8153
8154 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8155 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8156 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8157 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8158 Value *In = ICI->getOperand(0);
8159 Value *Sh = ConstantInt::get(In->getType(),
8160 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008161 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00008162 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008163 CI);
8164 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008165 In = CastInst::CreateIntegerCast(In, CI.getType(),
Chris Lattner8a9f5712007-04-11 06:57:46 +00008166 true/*SExt*/, "tmp", &CI);
8167
8168 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008169 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Chris Lattner8a9f5712007-04-11 06:57:46 +00008170 In->getName()+".not"), CI);
8171
8172 return ReplaceInstUsesWith(CI, In);
8173 }
8174 }
8175 }
Dan Gohmanf35c8822008-05-20 21:01:12 +00008176
8177 // See if the value being truncated is already sign extended. If so, just
8178 // eliminate the trunc/sext pair.
8179 if (getOpcode(Src) == Instruction::Trunc) {
8180 Value *Op = cast<User>(Src)->getOperand(0);
8181 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8182 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8183 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8184 unsigned NumSignBits = ComputeNumSignBits(Op);
8185
8186 if (OpBits == DestBits) {
8187 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8188 // bits, it is already ready.
8189 if (NumSignBits > DestBits-MidBits)
8190 return ReplaceInstUsesWith(CI, Op);
8191 } else if (OpBits < DestBits) {
8192 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8193 // bits, just sext from i32.
8194 if (NumSignBits > OpBits-MidBits)
8195 return new SExtInst(Op, CI.getType(), "tmp");
8196 } else {
8197 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8198 // bits, just truncate to i32.
8199 if (NumSignBits > OpBits-MidBits)
8200 return new TruncInst(Op, CI.getType(), "tmp");
8201 }
8202 }
Chris Lattner8a9f5712007-04-11 06:57:46 +00008203
Chris Lattnerba417832007-04-11 06:12:58 +00008204 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008205}
8206
Chris Lattnerb7530652008-01-27 05:29:54 +00008207/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8208/// in the specified FP type without changing its value.
Chris Lattner02a260a2008-04-20 00:41:09 +00008209static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008210 APFloat F = CFP->getValueAPF();
8211 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner02a260a2008-04-20 00:41:09 +00008212 return ConstantFP::get(F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008213 return 0;
8214}
8215
8216/// LookThroughFPExtensions - If this is an fp extension instruction, look
8217/// through it until we get the source value.
8218static Value *LookThroughFPExtensions(Value *V) {
8219 if (Instruction *I = dyn_cast<Instruction>(V))
8220 if (I->getOpcode() == Instruction::FPExt)
8221 return LookThroughFPExtensions(I->getOperand(0));
8222
8223 // If this value is a constant, return the constant in the smallest FP type
8224 // that can accurately represent it. This allows us to turn
8225 // (float)((double)X+2.0) into x+2.0f.
8226 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8227 if (CFP->getType() == Type::PPC_FP128Ty)
8228 return V; // No constant folding of this.
8229 // See if the value can be truncated to float and then reextended.
Chris Lattner02a260a2008-04-20 00:41:09 +00008230 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerb7530652008-01-27 05:29:54 +00008231 return V;
8232 if (CFP->getType() == Type::DoubleTy)
8233 return V; // Won't shrink.
Chris Lattner02a260a2008-04-20 00:41:09 +00008234 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerb7530652008-01-27 05:29:54 +00008235 return V;
8236 // Don't try to shrink to various long double types.
8237 }
8238
8239 return V;
8240}
8241
8242Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8243 if (Instruction *I = commonCastTransforms(CI))
8244 return I;
8245
8246 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8247 // smaller than the destination type, we can eliminate the truncate by doing
8248 // the add as the smaller type. This applies to add/sub/mul/div as well as
8249 // many builtins (sqrt, etc).
8250 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8251 if (OpI && OpI->hasOneUse()) {
8252 switch (OpI->getOpcode()) {
8253 default: break;
8254 case Instruction::Add:
8255 case Instruction::Sub:
8256 case Instruction::Mul:
8257 case Instruction::FDiv:
8258 case Instruction::FRem:
8259 const Type *SrcTy = OpI->getType();
8260 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8261 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8262 if (LHSTrunc->getType() != SrcTy &&
8263 RHSTrunc->getType() != SrcTy) {
8264 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8265 // If the source types were both smaller than the destination type of
8266 // the cast, do this xform.
8267 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8268 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8269 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8270 CI.getType(), CI);
8271 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8272 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008273 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008274 }
8275 }
8276 break;
8277 }
8278 }
8279 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008280}
8281
8282Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8283 return commonCastTransforms(CI);
8284}
8285
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008286Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8287 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8288 // mantissa to accurately represent all values of X. For example, do not
8289 // do this with i64->float->i64.
8290 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8291 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8292 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
Chris Lattner7be1c452008-05-19 21:17:23 +00008293 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008294 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8295
8296 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008297}
8298
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008299Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8300 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8301 // mantissa to accurately represent all values of X. For example, do not
8302 // do this with i64->float->i64.
8303 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8304 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8305 (int)FI.getType()->getPrimitiveSizeInBits() <=
Chris Lattner7be1c452008-05-19 21:17:23 +00008306 SrcI->getType()->getFPMantissaWidth())
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008307 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8308
8309 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008310}
8311
8312Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8313 return commonCastTransforms(CI);
8314}
8315
8316Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8317 return commonCastTransforms(CI);
8318}
8319
8320Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008321 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008322}
8323
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008324Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8325 if (Instruction *I = commonCastTransforms(CI))
8326 return I;
8327
8328 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8329 if (!DestPointee->isSized()) return 0;
8330
8331 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8332 ConstantInt *Cst;
8333 Value *X;
8334 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8335 m_ConstantInt(Cst)))) {
8336 // If the source and destination operands have the same type, see if this
8337 // is a single-index GEP.
8338 if (X->getType() == CI.getType()) {
8339 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00008340 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008341
8342 // Convert the constant to intptr type.
8343 APInt Offset = Cst->getValue();
8344 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8345
8346 // If Offset is evenly divisible by Size, we can do this xform.
8347 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8348 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greif051a9502008-04-06 20:25:17 +00008349 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008350 }
8351 }
8352 // TODO: Could handle other cases, e.g. where add is indexing into field of
8353 // struct etc.
8354 } else if (CI.getOperand(0)->hasOneUse() &&
8355 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8356 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8357 // "inttoptr+GEP" instead of "add+intptr".
8358
8359 // Get the size of the pointee type.
8360 uint64_t Size = TD->getABITypeSize(DestPointee);
8361
8362 // Convert the constant to intptr type.
8363 APInt Offset = Cst->getValue();
8364 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8365
8366 // If Offset is evenly divisible by Size, we can do this xform.
8367 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8368 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8369
8370 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8371 "tmp"), CI);
Gabor Greif051a9502008-04-06 20:25:17 +00008372 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008373 }
8374 }
8375 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008376}
8377
Chris Lattnerd3e28342007-04-27 17:44:50 +00008378Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008379 // If the operands are integer typed then apply the integer transforms,
8380 // otherwise just apply the common ones.
8381 Value *Src = CI.getOperand(0);
8382 const Type *SrcTy = Src->getType();
8383 const Type *DestTy = CI.getType();
8384
Chris Lattner42a75512007-01-15 02:27:26 +00008385 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008386 if (Instruction *Result = commonIntCastTransforms(CI))
8387 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00008388 } else if (isa<PointerType>(SrcTy)) {
8389 if (Instruction *I = commonPointerCastTransforms(CI))
8390 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008391 } else {
8392 if (Instruction *Result = commonCastTransforms(CI))
8393 return Result;
8394 }
8395
8396
8397 // Get rid of casts from one type to the same type. These are useless and can
8398 // be replaced by the operand.
8399 if (DestTy == Src->getType())
8400 return ReplaceInstUsesWith(CI, Src);
8401
Reid Spencer3da59db2006-11-27 01:05:10 +00008402 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008403 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8404 const Type *DstElTy = DstPTy->getElementType();
8405 const Type *SrcElTy = SrcPTy->getElementType();
8406
Nate Begeman83ad90a2008-03-31 00:22:16 +00008407 // If the address spaces don't match, don't eliminate the bitcast, which is
8408 // required for changing types.
8409 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8410 return 0;
8411
Chris Lattnerd3e28342007-04-27 17:44:50 +00008412 // If we are casting a malloc or alloca to a pointer to a type of the same
8413 // size, rewrite the allocation instruction to allocate the "right" type.
8414 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8415 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8416 return V;
8417
Chris Lattnerd717c182007-05-05 22:32:24 +00008418 // If the source and destination are pointers, and this cast is equivalent
8419 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008420 // This can enhance SROA and other transforms that want type-safe pointers.
8421 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8422 unsigned NumZeros = 0;
8423 while (SrcElTy != DstElTy &&
8424 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8425 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8426 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8427 ++NumZeros;
8428 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008429
Chris Lattnerd3e28342007-04-27 17:44:50 +00008430 // If we found a path from the src to dest, create the getelementptr now.
8431 if (SrcElTy == DstElTy) {
8432 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greif051a9502008-04-06 20:25:17 +00008433 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8434 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008435 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008436 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008437
Reid Spencer3da59db2006-11-27 01:05:10 +00008438 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8439 if (SVI->hasOneUse()) {
8440 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8441 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008442 if (isa<VectorType>(DestTy) &&
8443 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00008444 SVI->getType()->getNumElements()) {
8445 CastInst *Tmp;
8446 // If either of the operands is a cast from CI.getType(), then
8447 // evaluating the shuffle in the casted destination's type will allow
8448 // us to eliminate at least one cast.
8449 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8450 Tmp->getOperand(0)->getType() == DestTy) ||
8451 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8452 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00008453 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8454 SVI->getOperand(0), DestTy, &CI);
8455 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8456 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008457 // Return a new shuffle vector. Use the same element ID's, as we
8458 // know the vector types match #elts.
8459 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008460 }
8461 }
8462 }
8463 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008464 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008465}
8466
Chris Lattnere576b912004-04-09 23:46:01 +00008467/// GetSelectFoldableOperands - We want to turn code that looks like this:
8468/// %C = or %A, %B
8469/// %D = select %cond, %C, %A
8470/// into:
8471/// %C = select %cond, %B, 0
8472/// %D = or %A, %C
8473///
8474/// Assuming that the specified instruction is an operand to the select, return
8475/// a bitmask indicating which operands of this instruction are foldable if they
8476/// equal the other incoming value of the select.
8477///
8478static unsigned GetSelectFoldableOperands(Instruction *I) {
8479 switch (I->getOpcode()) {
8480 case Instruction::Add:
8481 case Instruction::Mul:
8482 case Instruction::And:
8483 case Instruction::Or:
8484 case Instruction::Xor:
8485 return 3; // Can fold through either operand.
8486 case Instruction::Sub: // Can only fold on the amount subtracted.
8487 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008488 case Instruction::LShr:
8489 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008490 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008491 default:
8492 return 0; // Cannot fold
8493 }
8494}
8495
8496/// GetSelectFoldableConstant - For the same transformation as the previous
8497/// function, return the identity constant that goes into the select.
8498static Constant *GetSelectFoldableConstant(Instruction *I) {
8499 switch (I->getOpcode()) {
8500 default: assert(0 && "This cannot happen!"); abort();
8501 case Instruction::Add:
8502 case Instruction::Sub:
8503 case Instruction::Or:
8504 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008505 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008506 case Instruction::LShr:
8507 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00008508 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008509 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00008510 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008511 case Instruction::Mul:
8512 return ConstantInt::get(I->getType(), 1);
8513 }
8514}
8515
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008516/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8517/// have the same opcode and only one use each. Try to simplify this.
8518Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8519 Instruction *FI) {
8520 if (TI->getNumOperands() == 1) {
8521 // If this is a non-volatile load or a cast from the same type,
8522 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008523 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008524 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8525 return 0;
8526 } else {
8527 return 0; // unknown unary op.
8528 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008529
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008530 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008531 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8532 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008533 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008534 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008535 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008536 }
8537
Reid Spencer832254e2007-02-02 02:16:23 +00008538 // Only handle binary operators here.
8539 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008540 return 0;
8541
8542 // Figure out if the operations have any operands in common.
8543 Value *MatchOp, *OtherOpT, *OtherOpF;
8544 bool MatchIsOpZero;
8545 if (TI->getOperand(0) == FI->getOperand(0)) {
8546 MatchOp = TI->getOperand(0);
8547 OtherOpT = TI->getOperand(1);
8548 OtherOpF = FI->getOperand(1);
8549 MatchIsOpZero = true;
8550 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8551 MatchOp = TI->getOperand(1);
8552 OtherOpT = TI->getOperand(0);
8553 OtherOpF = FI->getOperand(0);
8554 MatchIsOpZero = false;
8555 } else if (!TI->isCommutative()) {
8556 return 0;
8557 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8558 MatchOp = TI->getOperand(0);
8559 OtherOpT = TI->getOperand(1);
8560 OtherOpF = FI->getOperand(0);
8561 MatchIsOpZero = true;
8562 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8563 MatchOp = TI->getOperand(1);
8564 OtherOpT = TI->getOperand(0);
8565 OtherOpF = FI->getOperand(1);
8566 MatchIsOpZero = true;
8567 } else {
8568 return 0;
8569 }
8570
8571 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008572 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8573 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008574 InsertNewInstBefore(NewSI, SI);
8575
8576 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8577 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008578 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008579 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008580 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008581 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008582 assert(0 && "Shouldn't get here");
8583 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008584}
8585
Chris Lattner3d69f462004-03-12 05:52:32 +00008586Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008587 Value *CondVal = SI.getCondition();
8588 Value *TrueVal = SI.getTrueValue();
8589 Value *FalseVal = SI.getFalseValue();
8590
8591 // select true, X, Y -> X
8592 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008593 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00008594 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008595
8596 // select C, X, X -> X
8597 if (TrueVal == FalseVal)
8598 return ReplaceInstUsesWith(SI, TrueVal);
8599
Chris Lattnere87597f2004-10-16 18:11:37 +00008600 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8601 return ReplaceInstUsesWith(SI, FalseVal);
8602 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8603 return ReplaceInstUsesWith(SI, TrueVal);
8604 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8605 if (isa<Constant>(TrueVal))
8606 return ReplaceInstUsesWith(SI, TrueVal);
8607 else
8608 return ReplaceInstUsesWith(SI, FalseVal);
8609 }
8610
Reid Spencer4fe16d62007-01-11 18:21:29 +00008611 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00008612 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008613 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008614 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008615 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008616 } else {
8617 // Change: A = select B, false, C --> A = and !B, C
8618 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008619 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008620 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008621 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008622 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00008623 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00008624 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00008625 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008626 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008627 } else {
8628 // Change: A = select B, C, true --> A = or !B, C
8629 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008630 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00008631 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008632 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00008633 }
8634 }
Chris Lattnercfa59752007-11-25 21:27:53 +00008635
8636 // select a, b, a -> a&b
8637 // select a, a, b -> a|b
8638 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008639 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00008640 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008641 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008642 }
Chris Lattner0c199a72004-04-08 04:43:23 +00008643
Chris Lattner2eefe512004-04-09 19:05:30 +00008644 // Selecting between two integer constants?
8645 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8646 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00008647 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00008648 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008649 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00008650 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00008651 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00008652 Value *NotCond =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008653 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00008654 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008655 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00008656 }
Chris Lattnerba417832007-04-11 06:12:58 +00008657
8658 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00008659
Reid Spencere4d87aa2006-12-23 06:05:41 +00008660 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008661
Reid Spencere4d87aa2006-12-23 06:05:41 +00008662 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00008663 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00008664 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00008665 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00008666 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00008667 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00008668 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00008669 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00008670 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008671 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Reid Spencer832254e2007-02-02 02:16:23 +00008672 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00008673 InsertNewInstBefore(SRA, SI);
8674
Reid Spencer3da59db2006-11-27 01:05:10 +00008675 // Finally, convert to the type of the select RHS. We figure out
8676 // if this requires a SExt, Trunc or BitCast based on the sizes.
8677 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00008678 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8679 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008680 if (SRASize < SISize)
8681 opc = Instruction::SExt;
8682 else if (SRASize > SISize)
8683 opc = Instruction::Trunc;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008684 return CastInst::Create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00008685 }
8686 }
8687
8688
8689 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00008690 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00008691 // non-constant value, eliminate this whole mess. This corresponds to
8692 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00008693 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00008694 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008695 cast<Constant>(IC->getOperand(1))->isNullValue())
8696 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8697 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00008698 isa<ConstantInt>(ICA->getOperand(1)) &&
8699 (ICA->getOperand(1) == TrueValC ||
8700 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00008701 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8702 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00008703 // know whether we have a icmp_ne or icmp_eq and whether the
8704 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00008705 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00008706 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00008707 Value *V = ICA;
8708 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008709 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00008710 Instruction::Xor, V, ICA->getOperand(1)), SI);
8711 return ReplaceInstUsesWith(SI, V);
8712 }
Chris Lattnerb8456462006-09-20 04:44:59 +00008713 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00008714 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008715
8716 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008717 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8718 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00008719 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008720 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8721 // This is not safe in general for floating point:
8722 // consider X== -0, Y== +0.
8723 // It becomes safe if either operand is a nonzero constant.
8724 ConstantFP *CFPt, *CFPf;
8725 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8726 !CFPt->getValueAPF().isZero()) ||
8727 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8728 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00008729 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008730 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008731 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00008732 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00008733 return ReplaceInstUsesWith(SI, TrueVal);
8734 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8735
Reid Spencere4d87aa2006-12-23 06:05:41 +00008736 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00008737 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00008738 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8739 // This is not safe in general for floating point:
8740 // consider X== -0, Y== +0.
8741 // It becomes safe if either operand is a nonzero constant.
8742 ConstantFP *CFPt, *CFPf;
8743 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8744 !CFPt->getValueAPF().isZero()) ||
8745 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8746 !CFPf->getValueAPF().isZero()))
8747 return ReplaceInstUsesWith(SI, FalseVal);
8748 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00008749 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00008750 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8751 return ReplaceInstUsesWith(SI, TrueVal);
8752 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8753 }
8754 }
8755
8756 // See if we are selecting two values based on a comparison of the two values.
8757 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8758 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8759 // Transform (X == Y) ? X : Y -> Y
8760 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8761 return ReplaceInstUsesWith(SI, FalseVal);
8762 // Transform (X != Y) ? X : Y -> X
8763 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8764 return ReplaceInstUsesWith(SI, TrueVal);
8765 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8766
8767 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8768 // Transform (X == Y) ? Y : X -> X
8769 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8770 return ReplaceInstUsesWith(SI, FalseVal);
8771 // Transform (X != Y) ? Y : X -> Y
8772 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00008773 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00008774 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8775 }
8776 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008777
Chris Lattner87875da2005-01-13 22:52:24 +00008778 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8779 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8780 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00008781 Instruction *AddOp = 0, *SubOp = 0;
8782
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008783 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8784 if (TI->getOpcode() == FI->getOpcode())
8785 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8786 return IV;
8787
8788 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8789 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00008790 if (TI->getOpcode() == Instruction::Sub &&
8791 FI->getOpcode() == Instruction::Add) {
8792 AddOp = FI; SubOp = TI;
8793 } else if (FI->getOpcode() == Instruction::Sub &&
8794 TI->getOpcode() == Instruction::Add) {
8795 AddOp = TI; SubOp = FI;
8796 }
8797
8798 if (AddOp) {
8799 Value *OtherAddOp = 0;
8800 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8801 OtherAddOp = AddOp->getOperand(1);
8802 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8803 OtherAddOp = AddOp->getOperand(0);
8804 }
8805
8806 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00008807 // So at this point we know we have (Y -> OtherAddOp):
8808 // select C, (add X, Y), (sub X, Z)
8809 Value *NegVal; // Compute -Z
8810 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8811 NegVal = ConstantExpr::getNeg(C);
8812 } else {
8813 NegVal = InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008814 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00008815 }
Chris Lattner97f37a42006-02-24 18:05:58 +00008816
8817 Value *NewTrueOp = OtherAddOp;
8818 Value *NewFalseOp = NegVal;
8819 if (AddOp != TI)
8820 std::swap(NewTrueOp, NewFalseOp);
8821 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008822 SelectInst::Create(CondVal, NewTrueOp,
8823 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00008824
8825 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008826 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00008827 }
8828 }
8829 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008830
Chris Lattnere576b912004-04-09 23:46:01 +00008831 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00008832 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00008833 // See the comment above GetSelectFoldableOperands for a description of the
8834 // transformation we are doing here.
8835 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8836 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8837 !isa<Constant>(FalseVal))
8838 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8839 unsigned OpToFold = 0;
8840 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8841 OpToFold = 1;
8842 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8843 OpToFold = 2;
8844 }
8845
8846 if (OpToFold) {
8847 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008848 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008849 SelectInst::Create(SI.getCondition(),
8850 TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008851 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008852 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008853 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008854 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008855 else {
8856 assert(0 && "Unknown instruction!!");
8857 }
8858 }
8859 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008860
Chris Lattnere576b912004-04-09 23:46:01 +00008861 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8862 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8863 !isa<Constant>(TrueVal))
8864 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8865 unsigned OpToFold = 0;
8866 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8867 OpToFold = 1;
8868 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8869 OpToFold = 2;
8870 }
8871
8872 if (OpToFold) {
8873 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008874 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00008875 SelectInst::Create(SI.getCondition(), C,
8876 FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008877 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008878 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008879 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008880 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008881 else
Chris Lattnere576b912004-04-09 23:46:01 +00008882 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008883 }
8884 }
8885 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008886
8887 if (BinaryOperator::isNot(CondVal)) {
8888 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8889 SI.setOperand(1, FalseVal);
8890 SI.setOperand(2, TrueVal);
8891 return &SI;
8892 }
8893
Chris Lattner3d69f462004-03-12 05:52:32 +00008894 return 0;
8895}
8896
Dan Gohmaneee962e2008-04-10 18:43:06 +00008897/// EnforceKnownAlignment - If the specified pointer points to an object that
8898/// we control, modify the object's alignment to PrefAlign. This isn't
8899/// often possible though. If alignment is important, a more reliable approach
8900/// is to simply align all global variables and allocation instructions to
8901/// their preferred alignment from the beginning.
8902///
8903static unsigned EnforceKnownAlignment(Value *V,
8904 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008905
Dan Gohmaneee962e2008-04-10 18:43:06 +00008906 User *U = dyn_cast<User>(V);
8907 if (!U) return Align;
8908
8909 switch (getOpcode(U)) {
8910 default: break;
8911 case Instruction::BitCast:
8912 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8913 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00008914 // If all indexes are zero, it is just the alignment of the base pointer.
8915 bool AllZeroOperands = true;
Dan Gohmaneee962e2008-04-10 18:43:06 +00008916 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8917 if (!isa<Constant>(U->getOperand(i)) ||
8918 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008919 AllZeroOperands = false;
8920 break;
8921 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008922
8923 if (AllZeroOperands) {
8924 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00008925 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00008926 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008927 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00008928 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00008929 }
8930
8931 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8932 // If there is a large requested alignment and we can, bump up the alignment
8933 // of the global.
8934 if (!GV->isDeclaration()) {
8935 GV->setAlignment(PrefAlign);
8936 Align = PrefAlign;
8937 }
8938 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8939 // If there is a requested alignment and if this is an alloca, round up. We
8940 // don't do this for malloc, because some systems can't respect the request.
8941 if (isa<AllocaInst>(AI)) {
8942 AI->setAlignment(PrefAlign);
8943 Align = PrefAlign;
8944 }
8945 }
8946
8947 return Align;
8948}
8949
8950/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8951/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8952/// and it is more than the alignment of the ultimate object, see if we can
8953/// increase the alignment of the ultimate object, making this check succeed.
8954unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8955 unsigned PrefAlign) {
8956 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8957 sizeof(PrefAlign) * CHAR_BIT;
8958 APInt Mask = APInt::getAllOnesValue(BitWidth);
8959 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8960 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8961 unsigned TrailZ = KnownZero.countTrailingOnes();
8962 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8963
8964 if (PrefAlign > Align)
8965 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8966
8967 // We don't need to make any adjustment.
8968 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00008969}
8970
Chris Lattnerf497b022008-01-13 23:50:23 +00008971Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00008972 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8973 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00008974 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8975 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8976
8977 if (CopyAlign < MinAlign) {
8978 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8979 return MI;
8980 }
8981
8982 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8983 // load/store.
8984 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8985 if (MemOpLength == 0) return 0;
8986
Chris Lattner37ac6082008-01-14 00:28:35 +00008987 // Source and destination pointer types are always "i8*" for intrinsic. See
8988 // if the size is something we can handle with a single primitive load/store.
8989 // A single load+store correctly handles overlapping memory in the memmove
8990 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008991 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00008992 if (Size == 0) return MI; // Delete this mem transfer.
8993
8994 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008995 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008996
Chris Lattner37ac6082008-01-14 00:28:35 +00008997 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008998 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008999
9000 // Memcpy forces the use of i8* for the source and destination. That means
9001 // that if you're using memcpy to move one double around, you'll get a cast
9002 // from double* to i8*. We'd much rather use a double load+store rather than
9003 // an i64 load+store, here because this improves the odds that the source or
9004 // dest address will be promotable. See if we can find a better type than the
9005 // integer datatype.
9006 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9007 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9008 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9009 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9010 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009011 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009012 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9013 if (STy->getNumElements() == 1)
9014 SrcETy = STy->getElementType(0);
9015 else
9016 break;
9017 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9018 if (ATy->getNumElements() == 1)
9019 SrcETy = ATy->getElementType();
9020 else
9021 break;
9022 } else
9023 break;
9024 }
9025
Dan Gohman8f8e2692008-05-23 01:52:21 +00009026 if (SrcETy->isSingleValueType())
Chris Lattner37ac6082008-01-14 00:28:35 +00009027 NewPtrTy = PointerType::getUnqual(SrcETy);
9028 }
9029 }
9030
9031
Chris Lattnerf497b022008-01-13 23:50:23 +00009032 // If the memcpy/memmove provides better alignment info than we can
9033 // infer, use it.
9034 SrcAlign = std::max(SrcAlign, CopyAlign);
9035 DstAlign = std::max(DstAlign, CopyAlign);
9036
9037 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9038 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009039 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9040 InsertNewInstBefore(L, *MI);
9041 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9042
9043 // Set the size of the copy to 0, it will be deleted on the next iteration.
9044 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9045 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009046}
Chris Lattner3d69f462004-03-12 05:52:32 +00009047
Chris Lattner69ea9d22008-04-30 06:39:11 +00009048Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9049 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9050 if (MI->getAlignment()->getZExtValue() < Alignment) {
9051 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9052 return MI;
9053 }
9054
9055 // Extract the length and alignment and fill if they are constant.
9056 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9057 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9058 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9059 return 0;
9060 uint64_t Len = LenC->getZExtValue();
9061 Alignment = MI->getAlignment()->getZExtValue();
9062
9063 // If the length is zero, this is a no-op
9064 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9065
9066 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9067 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9068 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9069
9070 Value *Dest = MI->getDest();
9071 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9072
9073 // Alignment 0 is identity for alignment 1 for memset, but not store.
9074 if (Alignment == 0) Alignment = 1;
9075
9076 // Extract the fill value and store.
9077 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9078 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9079 Alignment), *MI);
9080
9081 // Set the size of the copy to 0, it will be deleted on the next iteration.
9082 MI->setLength(Constant::getNullValue(LenC->getType()));
9083 return MI;
9084 }
9085
9086 return 0;
9087}
9088
9089
Chris Lattner8b0ea312006-01-13 20:11:04 +00009090/// visitCallInst - CallInst simplification. This mostly only handles folding
9091/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9092/// the heavy lifting.
9093///
Chris Lattner9fe38862003-06-19 17:00:31 +00009094Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00009095 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9096 if (!II) return visitCallSite(&CI);
9097
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009098 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9099 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009100 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009101 bool Changed = false;
9102
9103 // memmove/cpy/set of zero bytes is a noop.
9104 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9105 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9106
Chris Lattner35b9e482004-10-12 04:52:52 +00009107 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009108 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009109 // Replace the instruction with just byte operations. We would
9110 // transform other cases to loads/stores, but we don't know if
9111 // alignment is sufficient.
9112 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009113 }
9114
Chris Lattner35b9e482004-10-12 04:52:52 +00009115 // If we have a memmove and the source operation is a constant global,
9116 // then the source and dest pointers can't alias, so we can change this
9117 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009118 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009119 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9120 if (GVSrc->isConstant()) {
9121 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00009122 Intrinsic::ID MemCpyID;
9123 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9124 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00009125 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00009126 MemCpyID = Intrinsic::memcpy_i64;
9127 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00009128 Changed = true;
9129 }
Chris Lattner95a959d2006-03-06 20:18:44 +00009130 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009131
Chris Lattner95a959d2006-03-06 20:18:44 +00009132 // If we can determine a pointer alignment that is bigger than currently
9133 // set, update the alignment.
9134 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009135 if (Instruction *I = SimplifyMemTransfer(MI))
9136 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009137 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9138 if (Instruction *I = SimplifyMemSet(MSI))
9139 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009140 }
9141
Chris Lattner8b0ea312006-01-13 20:11:04 +00009142 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009143 } else {
9144 switch (II->getIntrinsicID()) {
9145 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00009146 case Intrinsic::ppc_altivec_lvx:
9147 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009148 case Intrinsic::x86_sse_loadu_ps:
9149 case Intrinsic::x86_sse2_loadu_pd:
9150 case Intrinsic::x86_sse2_loadu_dq:
9151 // Turn PPC lvx -> load if the pointer is known aligned.
9152 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009153 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00009154 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9155 PointerType::getUnqual(II->getType()),
9156 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009157 return new LoadInst(Ptr);
9158 }
9159 break;
9160 case Intrinsic::ppc_altivec_stvx:
9161 case Intrinsic::ppc_altivec_stvxl:
9162 // Turn stvx -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009163 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009164 const Type *OpPtrTy =
9165 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009166 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00009167 return new StoreInst(II->getOperand(1), Ptr);
9168 }
9169 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009170 case Intrinsic::x86_sse_storeu_ps:
9171 case Intrinsic::x86_sse2_storeu_pd:
9172 case Intrinsic::x86_sse2_storeu_dq:
9173 case Intrinsic::x86_sse2_storel_dq:
9174 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009175 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009176 const Type *OpPtrTy =
9177 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00009178 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00009179 return new StoreInst(II->getOperand(2), Ptr);
9180 }
9181 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00009182
9183 case Intrinsic::x86_sse_cvttss2si: {
9184 // These intrinsics only demands the 0th element of its input vector. If
9185 // we can simplify the input based on that, do so now.
9186 uint64_t UndefElts;
9187 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9188 UndefElts)) {
9189 II->setOperand(1, V);
9190 return II;
9191 }
9192 break;
9193 }
9194
Chris Lattnere2ed0572006-04-06 19:19:17 +00009195 case Intrinsic::ppc_altivec_vperm:
9196 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009197 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00009198 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9199
9200 // Check that all of the elements are integer constants or undefs.
9201 bool AllEltsOk = true;
9202 for (unsigned i = 0; i != 16; ++i) {
9203 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9204 !isa<UndefValue>(Mask->getOperand(i))) {
9205 AllEltsOk = false;
9206 break;
9207 }
9208 }
9209
9210 if (AllEltsOk) {
9211 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00009212 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9213 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009214 Value *Result = UndefValue::get(Op0->getType());
9215
9216 // Only extract each element once.
9217 Value *ExtractedElts[32];
9218 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9219
9220 for (unsigned i = 0; i != 16; ++i) {
9221 if (isa<UndefValue>(Mask->getOperand(i)))
9222 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00009223 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00009224 Idx &= 31; // Match the hardware behavior.
9225
9226 if (ExtractedElts[Idx] == 0) {
9227 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00009228 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009229 InsertNewInstBefore(Elt, CI);
9230 ExtractedElts[Idx] = Elt;
9231 }
9232
9233 // Insert this value into the result vector.
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009234 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9235 i, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009236 InsertNewInstBefore(cast<Instruction>(Result), CI);
9237 }
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009238 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009239 }
9240 }
9241 break;
9242
Chris Lattnera728ddc2006-01-13 21:28:09 +00009243 case Intrinsic::stackrestore: {
9244 // If the save is right next to the restore, remove the restore. This can
9245 // happen when variable allocas are DCE'd.
9246 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9247 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9248 BasicBlock::iterator BI = SS;
9249 if (&*++BI == II)
9250 return EraseInstFromFunction(CI);
9251 }
9252 }
9253
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009254 // Scan down this block to see if there is another stack restore in the
9255 // same block without an intervening call/alloca.
9256 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00009257 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009258 bool CannotRemove = false;
9259 for (++BI; &*BI != TI; ++BI) {
9260 if (isa<AllocaInst>(BI)) {
9261 CannotRemove = true;
9262 break;
9263 }
9264 if (isa<CallInst>(BI)) {
9265 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00009266 CannotRemove = true;
9267 break;
9268 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009269 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00009270 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009271 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009272 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009273
9274 // If the stack restore is in a return/unwind block and if there are no
9275 // allocas or calls between the restore and the return, nuke the restore.
9276 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9277 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009278 break;
9279 }
9280 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009281 }
9282
Chris Lattner8b0ea312006-01-13 20:11:04 +00009283 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009284}
9285
9286// InvokeInst simplification
9287//
9288Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009289 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009290}
9291
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009292/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9293/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009294static bool isSafeToEliminateVarargsCast(const CallSite CS,
9295 const CastInst * const CI,
9296 const TargetData * const TD,
9297 const int ix) {
9298 if (!CI->isLosslessCast())
9299 return false;
9300
9301 // The size of ByVal arguments is derived from the type, so we
9302 // can't change to a type with a different size. If the size were
9303 // passed explicitly we could avoid this check.
9304 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9305 return true;
9306
9307 const Type* SrcTy =
9308 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9309 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9310 if (!SrcTy->isSized() || !DstTy->isSized())
9311 return false;
9312 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9313 return false;
9314 return true;
9315}
9316
Chris Lattnera44d8a22003-10-07 22:32:43 +00009317// visitCallSite - Improvements for call and invoke instructions.
9318//
9319Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009320 bool Changed = false;
9321
9322 // If the callee is a constexpr cast of a function, attempt to move the cast
9323 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009324 if (transformConstExprCastCall(CS)) return 0;
9325
Chris Lattner6c266db2003-10-07 22:54:13 +00009326 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009327
Chris Lattner08b22ec2005-05-13 07:09:09 +00009328 if (Function *CalleeF = dyn_cast<Function>(Callee))
9329 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9330 Instruction *OldCall = CS.getInstruction();
9331 // If the call and callee calling conventions don't match, this call must
9332 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009333 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009334 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9335 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009336 if (!OldCall->use_empty())
9337 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9338 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9339 return EraseInstFromFunction(*OldCall);
9340 return 0;
9341 }
9342
Chris Lattner17be6352004-10-18 02:59:09 +00009343 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9344 // This instruction is not reachable, just remove it. We insert a store to
9345 // undef so that we know that this code is not reachable, despite the fact
9346 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009347 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009348 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00009349 CS.getInstruction());
9350
9351 if (!CS.getInstruction()->use_empty())
9352 CS.getInstruction()->
9353 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9354
9355 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9356 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009357 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9358 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009359 }
Chris Lattner17be6352004-10-18 02:59:09 +00009360 return EraseInstFromFunction(*CS.getInstruction());
9361 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009362
Duncan Sandscdb6d922007-09-17 10:26:40 +00009363 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9364 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9365 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9366 return transformCallThroughTrampoline(CS);
9367
Chris Lattner6c266db2003-10-07 22:54:13 +00009368 const PointerType *PTy = cast<PointerType>(Callee->getType());
9369 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9370 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009371 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009372 // See if we can optimize any arguments passed through the varargs area of
9373 // the call.
9374 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009375 E = CS.arg_end(); I != E; ++I, ++ix) {
9376 CastInst *CI = dyn_cast<CastInst>(*I);
9377 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9378 *I = CI->getOperand(0);
9379 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009380 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009381 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009382 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009383
Duncan Sandsf0c33542007-12-19 21:13:37 +00009384 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009385 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009386 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009387 Changed = true;
9388 }
9389
Chris Lattner6c266db2003-10-07 22:54:13 +00009390 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009391}
9392
Chris Lattner9fe38862003-06-19 17:00:31 +00009393// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9394// attempt to move the cast to the arguments of the call/invoke.
9395//
9396bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9397 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9398 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009399 if (CE->getOpcode() != Instruction::BitCast ||
9400 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009401 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009402 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009403 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00009404 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00009405
9406 // Okay, this is a cast from a function to a different type. Unless doing so
9407 // would cause a type conversion of one of our arguments, change this call to
9408 // be a direct call with arguments casted to the appropriate types.
9409 //
9410 const FunctionType *FT = Callee->getFunctionType();
9411 const Type *OldRetTy = Caller->getType();
9412
Devang Patel75e6f022008-03-11 18:04:06 +00009413 if (isa<StructType>(FT->getReturnType()))
9414 return false; // TODO: Handle multiple return values.
9415
Chris Lattnerf78616b2004-01-14 06:06:08 +00009416 // Check to see if we are changing the return type...
9417 if (OldRetTy != FT->getReturnType()) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009418 if (Callee->isDeclaration() &&
Chris Lattner46013f42007-01-06 19:53:32 +00009419 // Conversion is ok if changing from pointer to int of same size.
9420 !(isa<PointerType>(FT->getReturnType()) &&
9421 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00009422 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009423
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009424 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009425 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00009426 FT->getReturnType() != Type::VoidTy &&
9427 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009428 return false; // Cannot transform this return value.
9429
Chris Lattner58d74912008-03-12 17:45:29 +00009430 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9431 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00009432 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9433 return false; // Attribute not compatible with transformed value.
9434 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009435
Chris Lattnerf78616b2004-01-14 06:06:08 +00009436 // If the callsite is an invoke instruction, and the return value is used by
9437 // a PHI node in a successor, we cannot change the return type of the call
9438 // because there is no place to put the cast instruction (without breaking
9439 // the critical edge). Bail out in this case.
9440 if (!Caller->use_empty())
9441 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9442 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9443 UI != E; ++UI)
9444 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9445 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009446 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009447 return false;
9448 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009449
9450 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9451 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009452
Chris Lattner9fe38862003-06-19 17:00:31 +00009453 CallSite::arg_iterator AI = CS.arg_begin();
9454 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9455 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009456 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009457
9458 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009459 return false; // Cannot transform this parameter value.
9460
Chris Lattner58d74912008-03-12 17:45:29 +00009461 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9462 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009463
Reid Spencer3da59db2006-11-27 01:05:10 +00009464 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009465 // Some conversions are safe even if we do not have a body.
9466 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00009467 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00009468 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00009469 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009470 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9471 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00009472 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00009473 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00009474 }
9475
9476 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00009477 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00009478 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00009479
Chris Lattner58d74912008-03-12 17:45:29 +00009480 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9481 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009482 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00009483 // won't be dropping them. Check that these extra arguments have attributes
9484 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00009485 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9486 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00009487 break;
Chris Lattner58d74912008-03-12 17:45:29 +00009488 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00009489 if (PAttrs & ParamAttr::VarArgsIncompatible)
9490 return false;
9491 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009492
Chris Lattner9fe38862003-06-19 17:00:31 +00009493 // Okay, we decided that this is a safe thing to do: go ahead and start
9494 // inserting cast instructions as necessary...
9495 std::vector<Value*> Args;
9496 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00009497 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009498 attrVec.reserve(NumCommonArgs);
9499
9500 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009501 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009502
9503 // If the return value is not being used, the type may not be compatible
9504 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00009505 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009506
9507 // Add the new return attributes.
9508 if (RAttrs)
9509 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009510
9511 AI = CS.arg_begin();
9512 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9513 const Type *ParamTy = FT->getParamType(i);
9514 if ((*AI)->getType() == ParamTy) {
9515 Args.push_back(*AI);
9516 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00009517 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00009518 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009519 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00009520 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00009521 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009522
9523 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009524 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009525 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00009526 }
9527
9528 // If the function takes more arguments than the call was taking, add them
9529 // now...
9530 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9531 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9532
9533 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009534 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009535 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00009536 cerr << "WARNING: While resolving call to function '"
9537 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00009538 } else {
9539 // Add all of the arguments in their promoted form to the arg list...
9540 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9541 const Type *PTy = getPromotedType((*AI)->getType());
9542 if (PTy != (*AI)->getType()) {
9543 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00009544 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9545 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009546 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00009547 InsertNewInstBefore(Cast, *Caller);
9548 Args.push_back(Cast);
9549 } else {
9550 Args.push_back(*AI);
9551 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009552
Duncan Sandse1e520f2008-01-13 08:02:44 +00009553 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009554 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00009555 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9556 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009557 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009558 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009559
9560 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00009561 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00009562
Chris Lattner58d74912008-03-12 17:45:29 +00009563 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009564
Chris Lattner9fe38862003-06-19 17:00:31 +00009565 Instruction *NC;
9566 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009567 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009568 Args.begin(), Args.end(),
9569 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00009570 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009571 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009572 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009573 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9574 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00009575 CallInst *CI = cast<CallInst>(Caller);
9576 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00009577 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00009578 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009579 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00009580 }
9581
Chris Lattner6934a042007-02-11 01:23:03 +00009582 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00009583 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009584 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00009585 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00009586 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009587 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009588 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00009589
9590 // If this is an invoke instruction, we should insert it after the first
9591 // non-phi, instruction in the normal successor block.
9592 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9593 BasicBlock::iterator I = II->getNormalDest()->begin();
9594 while (isa<PHINode>(I)) ++I;
9595 InsertNewInstBefore(NC, *I);
9596 } else {
9597 // Otherwise, it's a call, just insert cast right after the call instr
9598 InsertNewInstBefore(NC, *Caller);
9599 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009600 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009601 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00009602 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00009603 }
9604 }
9605
9606 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9607 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00009608 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00009609 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00009610 return true;
9611}
9612
Duncan Sandscdb6d922007-09-17 10:26:40 +00009613// transformCallThroughTrampoline - Turn a call to a function created by the
9614// init_trampoline intrinsic into a direct call to the underlying function.
9615//
9616Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9617 Value *Callee = CS.getCalledValue();
9618 const PointerType *PTy = cast<PointerType>(Callee->getType());
9619 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00009620 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009621
9622 // If the call already has the 'nest' attribute somewhere then give up -
9623 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00009624 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009625 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009626
9627 IntrinsicInst *Tramp =
9628 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9629
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00009630 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009631 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9632 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9633
Chris Lattner58d74912008-03-12 17:45:29 +00009634 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9635 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009636 unsigned NestIdx = 1;
9637 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00009638 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009639
9640 // Look for a parameter marked with the 'nest' attribute.
9641 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9642 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00009643 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00009644 // Record the parameter type and any other attributes.
9645 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00009646 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009647 break;
9648 }
9649
9650 if (NestTy) {
9651 Instruction *Caller = CS.getInstruction();
9652 std::vector<Value*> NewArgs;
9653 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9654
Chris Lattner58d74912008-03-12 17:45:29 +00009655 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9656 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009657
Duncan Sandscdb6d922007-09-17 10:26:40 +00009658 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009659 // mean appending it. Likewise for attributes.
9660
9661 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00009662 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9663 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009664
Duncan Sandscdb6d922007-09-17 10:26:40 +00009665 {
9666 unsigned Idx = 1;
9667 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9668 do {
9669 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009670 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009671 Value *NestVal = Tramp->getOperand(3);
9672 if (NestVal->getType() != NestTy)
9673 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9674 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009675 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009676 }
9677
9678 if (I == E)
9679 break;
9680
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009681 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009682 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00009683 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009684 NewAttrs.push_back
9685 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00009686
9687 ++Idx, ++I;
9688 } while (1);
9689 }
9690
9691 // The trampoline may have been bitcast to a bogus type (FTy).
9692 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009693 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009694
Duncan Sandscdb6d922007-09-17 10:26:40 +00009695 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00009696 NewTypes.reserve(FTy->getNumParams()+1);
9697
Duncan Sandscdb6d922007-09-17 10:26:40 +00009698 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009699 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009700 {
9701 unsigned Idx = 1;
9702 FunctionType::param_iterator I = FTy->param_begin(),
9703 E = FTy->param_end();
9704
9705 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009706 if (Idx == NestIdx)
9707 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009708 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009709
9710 if (I == E)
9711 break;
9712
Duncan Sandsb0c9b932008-01-14 19:52:09 +00009713 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00009714 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009715
9716 ++Idx, ++I;
9717 } while (1);
9718 }
9719
9720 // Replace the trampoline call with a direct call. Let the generic
9721 // code sort out any function type mismatches.
9722 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00009723 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009724 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9725 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00009726 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00009727
9728 Instruction *NewCaller;
9729 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +00009730 NewCaller = InvokeInst::Create(NewCallee,
9731 II->getNormalDest(), II->getUnwindDest(),
9732 NewArgs.begin(), NewArgs.end(),
9733 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009734 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009735 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009736 } else {
Gabor Greif051a9502008-04-06 20:25:17 +00009737 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9738 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009739 if (cast<CallInst>(Caller)->isTailCall())
9740 cast<CallInst>(NewCaller)->setTailCall();
9741 cast<CallInst>(NewCaller)->
9742 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00009743 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00009744 }
9745 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9746 Caller->replaceAllUsesWith(NewCaller);
9747 Caller->eraseFromParent();
9748 RemoveFromWorkList(Caller);
9749 return 0;
9750 }
9751 }
9752
9753 // Replace the trampoline call with a direct call. Since there is no 'nest'
9754 // parameter, there is no need to adjust the argument list. Let the generic
9755 // code sort out any function type mismatches.
9756 Constant *NewCallee =
9757 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9758 CS.setCalledFunction(NewCallee);
9759 return CS.getInstruction();
9760}
9761
Chris Lattner7da52b22006-11-01 04:51:18 +00009762/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9763/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9764/// and a single binop.
9765Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9766 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00009767 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9768 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00009769 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009770 Value *LHSVal = FirstInst->getOperand(0);
9771 Value *RHSVal = FirstInst->getOperand(1);
9772
9773 const Type *LHSType = LHSVal->getType();
9774 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00009775
9776 // Scan to see if all operands are the same opcode, all have one use, and all
9777 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00009778 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00009779 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00009780 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00009781 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00009782 // types or GEP's with different index types.
9783 I->getOperand(0)->getType() != LHSType ||
9784 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00009785 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00009786
9787 // If they are CmpInst instructions, check their predicates
9788 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9789 if (cast<CmpInst>(I)->getPredicate() !=
9790 cast<CmpInst>(FirstInst)->getPredicate())
9791 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009792
9793 // Keep track of which operand needs a phi node.
9794 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9795 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00009796 }
9797
Chris Lattner53738a42006-11-08 19:42:28 +00009798 // Otherwise, this is safe to transform, determine if it is profitable.
9799
9800 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9801 // Indexes are often folded into load/store instructions, so we don't want to
9802 // hide them behind a phi.
9803 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9804 return 0;
9805
Chris Lattner7da52b22006-11-01 04:51:18 +00009806 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00009807 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00009808 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009809 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009810 NewLHS = PHINode::Create(LHSType,
9811 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009812 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9813 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009814 InsertNewInstBefore(NewLHS, PN);
9815 LHSVal = NewLHS;
9816 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009817
9818 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009819 NewRHS = PHINode::Create(RHSType,
9820 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009821 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9822 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00009823 InsertNewInstBefore(NewRHS, PN);
9824 RHSVal = NewRHS;
9825 }
9826
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00009827 // Add all operands to the new PHIs.
9828 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9829 if (NewLHS) {
9830 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9831 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9832 }
9833 if (NewRHS) {
9834 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9835 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9836 }
9837 }
9838
Chris Lattner7da52b22006-11-01 04:51:18 +00009839 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009840 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009841 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009842 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Reid Spencere4d87aa2006-12-23 06:05:41 +00009843 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009844 else {
9845 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greif051a9502008-04-06 20:25:17 +00009846 return GetElementPtrInst::Create(LHSVal, RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00009847 }
Chris Lattner7da52b22006-11-01 04:51:18 +00009848}
9849
Chris Lattner76c73142006-11-01 07:13:54 +00009850/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9851/// of the block that defines it. This means that it must be obvious the value
9852/// of the load is not changed from the point of the load to the end of the
9853/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009854///
9855/// Finally, it is safe, but not profitable, to sink a load targetting a
9856/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9857/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00009858static bool isSafeToSinkLoad(LoadInst *L) {
9859 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9860
9861 for (++BBI; BBI != E; ++BBI)
9862 if (BBI->mayWriteToMemory())
9863 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00009864
9865 // Check for non-address taken alloca. If not address-taken already, it isn't
9866 // profitable to do this xform.
9867 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9868 bool isAddressTaken = false;
9869 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9870 UI != E; ++UI) {
9871 if (isa<LoadInst>(UI)) continue;
9872 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9873 // If storing TO the alloca, then the address isn't taken.
9874 if (SI->getOperand(1) == AI) continue;
9875 }
9876 isAddressTaken = true;
9877 break;
9878 }
9879
9880 if (!isAddressTaken)
9881 return false;
9882 }
9883
Chris Lattner76c73142006-11-01 07:13:54 +00009884 return true;
9885}
9886
Chris Lattner9fe38862003-06-19 17:00:31 +00009887
Chris Lattnerbac32862004-11-14 19:13:23 +00009888// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9889// operator and they all are only used by the PHI, PHI together their
9890// inputs, and do the operation once, to the result of the PHI.
9891Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9892 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9893
9894 // Scan the instruction, looking for input operations that can be folded away.
9895 // If all input operands to the phi are the same instruction (e.g. a cast from
9896 // the same type or "+42") we can pull the operation through the PHI, reducing
9897 // code size and simplifying code.
9898 Constant *ConstantOp = 0;
9899 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009900 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009901 if (isa<CastInst>(FirstInst)) {
9902 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009903 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009904 // Can fold binop, compare or shift here if the RHS is a constant,
9905 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009906 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009907 if (ConstantOp == 0)
9908 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009909 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9910 isVolatile = LI->isVolatile();
9911 // We can't sink the load if the loaded value could be modified between the
9912 // load and the PHI.
9913 if (LI->getParent() != PN.getIncomingBlock(0) ||
9914 !isSafeToSinkLoad(LI))
9915 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009916 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009917 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009918 return FoldPHIArgBinOpIntoPHI(PN);
9919 // Can't handle general GEPs yet.
9920 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009921 } else {
9922 return 0; // Cannot fold this operation.
9923 }
9924
9925 // Check to see if all arguments are the same operation.
9926 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9927 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9928 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009929 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009930 return 0;
9931 if (CastSrcTy) {
9932 if (I->getOperand(0)->getType() != CastSrcTy)
9933 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009934 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009935 // We can't sink the load if the loaded value could be modified between
9936 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009937 if (LI->isVolatile() != isVolatile ||
9938 LI->getParent() != PN.getIncomingBlock(i) ||
9939 !isSafeToSinkLoad(LI))
9940 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +00009941
9942 // If the PHI is volatile and its block has multiple successors, sinking
9943 // it would remove a load of the volatile value from the path through the
9944 // other successor.
9945 if (isVolatile &&
9946 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9947 return 0;
9948
9949
Chris Lattnerbac32862004-11-14 19:13:23 +00009950 } else if (I->getOperand(1) != ConstantOp) {
9951 return 0;
9952 }
9953 }
9954
9955 // Okay, they are all the same operation. Create a new PHI node of the
9956 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +00009957 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9958 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009959 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009960
9961 Value *InVal = FirstInst->getOperand(0);
9962 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009963
9964 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009965 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9966 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9967 if (NewInVal != InVal)
9968 InVal = 0;
9969 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9970 }
9971
9972 Value *PhiVal;
9973 if (InVal) {
9974 // The new PHI unions all of the same values together. This is really
9975 // common, so we handle it intelligently here for compile-time speed.
9976 PhiVal = InVal;
9977 delete NewPN;
9978 } else {
9979 InsertNewInstBefore(NewPN, PN);
9980 PhiVal = NewPN;
9981 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009982
Chris Lattnerbac32862004-11-14 19:13:23 +00009983 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009984 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009985 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +00009986 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009987 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009988 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009989 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00009990 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +00009991 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9992
9993 // If this was a volatile load that we are merging, make sure to loop through
9994 // and mark all the input loads as non-volatile. If we don't do this, we will
9995 // insert a new volatile load and the old ones will not be deletable.
9996 if (isVolatile)
9997 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9998 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9999
10000 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010001}
Chris Lattnera1be5662002-05-02 17:06:02 +000010002
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010003/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10004/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010005static bool DeadPHICycle(PHINode *PN,
10006 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010007 if (PN->use_empty()) return true;
10008 if (!PN->hasOneUse()) return false;
10009
10010 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010011 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010012 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010013
10014 // Don't scan crazily complex things.
10015 if (PotentiallyDeadPHIs.size() == 16)
10016 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010017
10018 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10019 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010020
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010021 return false;
10022}
10023
Chris Lattnercf5008a2007-11-06 21:52:06 +000010024/// PHIsEqualValue - Return true if this phi node is always equal to
10025/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10026/// z = some value; x = phi (y, z); y = phi (x, z)
10027static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10028 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10029 // See if we already saw this PHI node.
10030 if (!ValueEqualPHIs.insert(PN))
10031 return true;
10032
10033 // Don't scan crazily complex things.
10034 if (ValueEqualPHIs.size() == 16)
10035 return false;
10036
10037 // Scan the operands to see if they are either phi nodes or are equal to
10038 // the value.
10039 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10040 Value *Op = PN->getIncomingValue(i);
10041 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10042 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10043 return false;
10044 } else if (Op != NonPhiInVal)
10045 return false;
10046 }
10047
10048 return true;
10049}
10050
10051
Chris Lattner473945d2002-05-06 18:06:38 +000010052// PHINode simplification
10053//
Chris Lattner7e708292002-06-25 16:13:24 +000010054Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010055 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010056 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010057
Owen Anderson7e057142006-07-10 22:03:18 +000010058 if (Value *V = PN.hasConstantValue())
10059 return ReplaceInstUsesWith(PN, V);
10060
Owen Anderson7e057142006-07-10 22:03:18 +000010061 // If all PHI operands are the same operation, pull them through the PHI,
10062 // reducing code size.
10063 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10064 PN.getIncomingValue(0)->hasOneUse())
10065 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10066 return Result;
10067
10068 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10069 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10070 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010071 if (PN.hasOneUse()) {
10072 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10073 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010074 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010075 PotentiallyDeadPHIs.insert(&PN);
10076 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10077 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10078 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010079
10080 // If this phi has a single use, and if that use just computes a value for
10081 // the next iteration of a loop, delete the phi. This occurs with unused
10082 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10083 // common case here is good because the only other things that catch this
10084 // are induction variable analysis (sometimes) and ADCE, which is only run
10085 // late.
10086 if (PHIUser->hasOneUse() &&
10087 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10088 PHIUser->use_back() == &PN) {
10089 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10090 }
10091 }
Owen Anderson7e057142006-07-10 22:03:18 +000010092
Chris Lattnercf5008a2007-11-06 21:52:06 +000010093 // We sometimes end up with phi cycles that non-obviously end up being the
10094 // same value, for example:
10095 // z = some value; x = phi (y, z); y = phi (x, z)
10096 // where the phi nodes don't necessarily need to be in the same block. Do a
10097 // quick check to see if the PHI node only contains a single non-phi value, if
10098 // so, scan to see if the phi cycle is actually equal to that value.
10099 {
10100 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10101 // Scan for the first non-phi operand.
10102 while (InValNo != NumOperandVals &&
10103 isa<PHINode>(PN.getIncomingValue(InValNo)))
10104 ++InValNo;
10105
10106 if (InValNo != NumOperandVals) {
10107 Value *NonPhiInVal = PN.getOperand(InValNo);
10108
10109 // Scan the rest of the operands to see if there are any conflicts, if so
10110 // there is no need to recursively scan other phis.
10111 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10112 Value *OpVal = PN.getIncomingValue(InValNo);
10113 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10114 break;
10115 }
10116
10117 // If we scanned over all operands, then we have one unique value plus
10118 // phi values. Scan PHI nodes to see if they all merge in each other or
10119 // the value.
10120 if (InValNo == NumOperandVals) {
10121 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10122 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10123 return ReplaceInstUsesWith(PN, NonPhiInVal);
10124 }
10125 }
10126 }
Chris Lattner60921c92003-12-19 05:58:40 +000010127 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010128}
10129
Reid Spencer17212df2006-12-12 09:18:51 +000010130static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10131 Instruction *InsertPoint,
10132 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +000010133 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10134 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +000010135 // We must cast correctly to the pointer type. Ensure that we
10136 // sign extend the integer value if it is smaller as this is
10137 // used for address computation.
10138 Instruction::CastOps opcode =
10139 (VTySize < PtrSize ? Instruction::SExt :
10140 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10141 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +000010142}
10143
Chris Lattnera1be5662002-05-02 17:06:02 +000010144
Chris Lattner7e708292002-06-25 16:13:24 +000010145Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010146 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010147 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010148 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010149 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010150 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010151
Chris Lattnere87597f2004-10-16 18:11:37 +000010152 if (isa<UndefValue>(GEP.getOperand(0)))
10153 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10154
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010155 bool HasZeroPointerIndex = false;
10156 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10157 HasZeroPointerIndex = C->isNullValue();
10158
10159 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010160 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010161
Chris Lattner28977af2004-04-05 01:30:19 +000010162 // Eliminate unneeded casts for indices.
10163 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010164
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010165 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010166 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010167 if (isa<SequentialType>(*GTI)) {
10168 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +000010169 if (CI->getOpcode() == Instruction::ZExt ||
10170 CI->getOpcode() == Instruction::SExt) {
10171 const Type *SrcTy = CI->getOperand(0)->getType();
10172 // We can eliminate a cast from i32 to i64 iff the target
10173 // is a 32-bit pointer target.
10174 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10175 MadeChange = true;
10176 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +000010177 }
10178 }
10179 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010180 // If we are using a wider index than needed for this platform, shrink it
10181 // to what we need. If the incoming value needs a cast instruction,
10182 // insert it. This explicit cast can make subsequent optimizations more
10183 // obvious.
10184 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010185 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +000010186 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010187 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +000010188 MadeChange = true;
10189 } else {
Reid Spencer17212df2006-12-12 09:18:51 +000010190 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10191 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010192 GEP.setOperand(i, Op);
10193 MadeChange = true;
10194 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010195 }
Chris Lattner28977af2004-04-05 01:30:19 +000010196 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010197 }
Chris Lattner28977af2004-04-05 01:30:19 +000010198 if (MadeChange) return &GEP;
10199
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010200 // If this GEP instruction doesn't move the pointer, and if the input operand
10201 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10202 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +000010203 if (GEP.hasAllZeroIndices()) {
10204 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10205 // If the bitcast is of an allocation, and the allocation will be
10206 // converted to match the type of the cast, don't touch this.
10207 if (isa<AllocationInst>(BCI->getOperand(0))) {
10208 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +000010209 if (Instruction *I = visitBitCast(*BCI)) {
10210 if (I != BCI) {
10211 I->takeName(BCI);
10212 BCI->getParent()->getInstList().insert(BCI, I);
10213 ReplaceInstUsesWith(*BCI, I);
10214 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010215 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +000010216 }
Chris Lattner6a94de22007-10-12 05:30:59 +000010217 }
10218 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10219 }
10220 }
10221
Chris Lattner90ac28c2002-08-02 19:29:35 +000010222 // Combine Indices - If the source pointer to this getelementptr instruction
10223 // is a getelementptr instruction, combine the indices of the two
10224 // getelementptr instructions into a single instruction.
10225 //
Chris Lattner72588fc2007-02-15 22:48:32 +000010226 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +000010227 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +000010228 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +000010229
10230 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +000010231 // Note that if our source is a gep chain itself that we wait for that
10232 // chain to be resolved before we perform this transformation. This
10233 // avoids us creating a TON of code in some cases.
10234 //
10235 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10236 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10237 return 0; // Wait until our source is folded to completion.
10238
Chris Lattner72588fc2007-02-15 22:48:32 +000010239 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010240
10241 // Find out whether the last index in the source GEP is a sequential idx.
10242 bool EndsWithSequential = false;
10243 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10244 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010245 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010246
Chris Lattner90ac28c2002-08-02 19:29:35 +000010247 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010248 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010249 // Replace: gep (gep %P, long B), long A, ...
10250 // With: T = long A+B; gep %P, T, ...
10251 //
Chris Lattner620ce142004-05-07 22:09:22 +000010252 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +000010253 if (SO1 == Constant::getNullValue(SO1->getType())) {
10254 Sum = GO1;
10255 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10256 Sum = SO1;
10257 } else {
10258 // If they aren't the same type, convert both to an integer of the
10259 // target's pointer size.
10260 if (SO1->getType() != GO1->getType()) {
10261 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010262 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010263 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +000010264 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +000010265 } else {
Duncan Sands514ab342007-11-01 20:53:16 +000010266 unsigned PS = TD->getPointerSizeInBits();
10267 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010268 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010269 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010270
Duncan Sands514ab342007-11-01 20:53:16 +000010271 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +000010272 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +000010273 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010274 } else {
10275 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +000010276 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10277 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +000010278 }
10279 }
10280 }
Chris Lattner620ce142004-05-07 22:09:22 +000010281 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10282 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10283 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010284 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010285 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010286 }
Chris Lattner28977af2004-04-05 01:30:19 +000010287 }
Chris Lattner620ce142004-05-07 22:09:22 +000010288
10289 // Recycle the GEP we already have if possible.
10290 if (SrcGEPOperands.size() == 2) {
10291 GEP.setOperand(0, SrcGEPOperands[0]);
10292 GEP.setOperand(1, Sum);
10293 return &GEP;
10294 } else {
10295 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10296 SrcGEPOperands.end()-1);
10297 Indices.push_back(Sum);
10298 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10299 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010300 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010301 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010302 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010303 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +000010304 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10305 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010306 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10307 }
10308
10309 if (!Indices.empty())
Gabor Greif051a9502008-04-06 20:25:17 +000010310 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10311 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +000010312
Chris Lattner620ce142004-05-07 22:09:22 +000010313 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +000010314 // GEP of global variable. If all of the indices for this GEP are
10315 // constants, we can promote this to a constexpr instead of an instruction.
10316
10317 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010318 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +000010319 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10320 for (; I != E && isa<Constant>(*I); ++I)
10321 Indices.push_back(cast<Constant>(*I));
10322
10323 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +000010324 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10325 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +000010326
10327 // Replace all uses of the GEP with the new constexpr...
10328 return ReplaceInstUsesWith(GEP, CE);
10329 }
Reid Spencer3da59db2006-11-27 01:05:10 +000010330 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +000010331 if (!isa<PointerType>(X->getType())) {
10332 // Not interesting. Source pointer must be a cast from pointer.
10333 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010334 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10335 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010336 //
10337 // This occurs when the program declares an array extern like "int X[];"
10338 //
10339 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10340 const PointerType *XTy = cast<PointerType>(X->getType());
10341 if (const ArrayType *XATy =
10342 dyn_cast<ArrayType>(XTy->getElementType()))
10343 if (const ArrayType *CATy =
10344 dyn_cast<ArrayType>(CPTy->getElementType()))
10345 if (CATy->getElementType() == XATy->getElementType()) {
10346 // At this point, we know that the cast source type is a pointer
10347 // to an array of the same type as the destination pointer
10348 // array. Because the array type is never stepped over (there
10349 // is a leading zero) we can fold the cast into this GEP.
10350 GEP.setOperand(0, X);
10351 return &GEP;
10352 }
10353 } else if (GEP.getNumOperands() == 2) {
10354 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010355 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10356 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010357 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10358 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10359 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +000010360 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10361 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010362 Value *Idx[2];
10363 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10364 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +000010365 Value *V = InsertNewInstBefore(
Gabor Greif051a9502008-04-06 20:25:17 +000010366 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000010367 // V and GEP are both pointer types --> BitCast
10368 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010369 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010370
10371 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010372 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010373 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010374 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010375
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010376 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010377 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +000010378 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010379
10380 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10381 // allow either a mul, shift, or constant here.
10382 Value *NewIdx = 0;
10383 ConstantInt *Scale = 0;
10384 if (ArrayEltSize == 1) {
10385 NewIdx = GEP.getOperand(1);
10386 Scale = ConstantInt::get(NewIdx->getType(), 1);
10387 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +000010388 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010389 Scale = CI;
10390 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10391 if (Inst->getOpcode() == Instruction::Shl &&
10392 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010393 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10394 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10395 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010396 NewIdx = Inst->getOperand(0);
10397 } else if (Inst->getOpcode() == Instruction::Mul &&
10398 isa<ConstantInt>(Inst->getOperand(1))) {
10399 Scale = cast<ConstantInt>(Inst->getOperand(1));
10400 NewIdx = Inst->getOperand(0);
10401 }
10402 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010403
Chris Lattner7835cdd2005-09-13 18:36:04 +000010404 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010405 // out, perform the transformation. Note, we don't know whether Scale is
10406 // signed or not. We'll use unsigned version of division/modulo
10407 // operation after making sure Scale doesn't have the sign bit set.
10408 if (Scale && Scale->getSExtValue() >= 0LL &&
10409 Scale->getZExtValue() % ArrayEltSize == 0) {
10410 Scale = ConstantInt::get(Scale->getType(),
10411 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010412 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +000010413 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010414 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010415 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000010416 NewIdx = InsertNewInstBefore(Sc, GEP);
10417 }
10418
10419 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000010420 Value *Idx[2];
10421 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10422 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000010423 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000010424 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000010425 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10426 // The NewGEP must be pointer typed, so must the old one -> BitCast
10427 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010428 }
10429 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010430 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010431 }
10432
Chris Lattner8a2a3112001-12-14 16:52:21 +000010433 return 0;
10434}
10435
Chris Lattner0864acf2002-11-04 16:18:53 +000010436Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10437 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010438 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000010439 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10440 const Type *NewTy =
10441 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000010442 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000010443
10444 // Create and insert the replacement instruction...
10445 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +000010446 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010447 else {
10448 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +000010449 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000010450 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010451
10452 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000010453
Chris Lattner0864acf2002-11-04 16:18:53 +000010454 // Scan to the end of the allocation instructions, to skip over a block of
10455 // allocas if possible...
10456 //
10457 BasicBlock::iterator It = New;
10458 while (isa<AllocationInst>(*It)) ++It;
10459
10460 // Now that I is pointing to the first non-allocation-inst in the block,
10461 // insert our getelementptr instruction...
10462 //
Reid Spencerc5b206b2006-12-31 05:48:39 +000010463 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +000010464 Value *Idx[2];
10465 Idx[0] = NullIdx;
10466 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000010467 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10468 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000010469
10470 // Now make everything use the getelementptr instead of the original
10471 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000010472 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000010473 } else if (isa<UndefValue>(AI.getArraySize())) {
10474 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000010475 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010476 }
Chris Lattner7c881df2004-03-19 06:08:10 +000010477
10478 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10479 // Note that we only do this for alloca's, because malloc should allocate and
10480 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +000010481 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +000010482 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +000010483 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10484
Chris Lattner0864acf2002-11-04 16:18:53 +000010485 return 0;
10486}
10487
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010488Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10489 Value *Op = FI.getOperand(0);
10490
Chris Lattner17be6352004-10-18 02:59:09 +000010491 // free undef -> unreachable.
10492 if (isa<UndefValue>(Op)) {
10493 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +000010494 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010495 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000010496 return EraseInstFromFunction(FI);
10497 }
Chris Lattner6fe55412007-04-14 00:20:02 +000010498
Chris Lattner6160e852004-02-28 04:57:37 +000010499 // If we have 'free null' delete the instruction. This can happen in stl code
10500 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000010501 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010502 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000010503
10504 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10505 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10506 FI.setOperand(0, CI->getOperand(0));
10507 return &FI;
10508 }
10509
10510 // Change free (gep X, 0,0,0,0) into free(X)
10511 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10512 if (GEPI->hasAllZeroIndices()) {
10513 AddToWorkList(GEPI);
10514 FI.setOperand(0, GEPI->getOperand(0));
10515 return &FI;
10516 }
10517 }
10518
10519 // Change free(malloc) into nothing, if the malloc has a single use.
10520 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10521 if (MI->hasOneUse()) {
10522 EraseInstFromFunction(FI);
10523 return EraseInstFromFunction(*MI);
10524 }
Chris Lattner6160e852004-02-28 04:57:37 +000010525
Chris Lattner67b1e1b2003-12-07 01:24:23 +000010526 return 0;
10527}
10528
10529
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010530/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000010531static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000010532 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010533 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000010534 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +000010535
Devang Patel99db6ad2007-10-18 19:52:32 +000010536 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10537 // Instead of loading constant c string, use corresponding integer value
10538 // directly if string length is small enough.
10539 const std::string &Str = CE->getOperand(0)->getStringValue();
10540 if (!Str.empty()) {
10541 unsigned len = Str.length();
10542 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10543 unsigned numBits = Ty->getPrimitiveSizeInBits();
10544 // Replace LI with immediate integer store.
10545 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +000010546 APInt StrVal(numBits, 0);
10547 APInt SingleChar(numBits, 0);
10548 if (TD->isLittleEndian()) {
10549 for (signed i = len-1; i >= 0; i--) {
10550 SingleChar = (uint64_t) Str[i];
10551 StrVal = (StrVal << 8) | SingleChar;
10552 }
10553 } else {
10554 for (unsigned i = 0; i < len; i++) {
10555 SingleChar = (uint64_t) Str[i];
10556 StrVal = (StrVal << 8) | SingleChar;
10557 }
10558 // Append NULL at the end.
10559 SingleChar = 0;
10560 StrVal = (StrVal << 8) | SingleChar;
10561 }
10562 Value *NL = ConstantInt::get(StrVal);
10563 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +000010564 }
10565 }
10566 }
10567
Chris Lattnerb89e0712004-07-13 01:49:43 +000010568 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010569 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000010570 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000010571
Reid Spencer42230162007-01-22 05:51:25 +000010572 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010573 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000010574 // If the source is an array, the code below will not succeed. Check to
10575 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10576 // constants.
10577 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10578 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10579 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010580 Value *Idxs[2];
10581 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10582 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000010583 SrcTy = cast<PointerType>(CastOp->getType());
10584 SrcPTy = SrcTy->getElementType();
10585 }
10586
Reid Spencer42230162007-01-22 05:51:25 +000010587 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000010588 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000010589 // Do not allow turning this into a load of an integer, which is then
10590 // casted to a pointer, this pessimizes pointer analysis a lot.
10591 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +000010592 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10593 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000010594
Chris Lattnerf9527852005-01-31 04:50:46 +000010595 // Okay, we are casting from one integer or pointer type to another of
10596 // the same size. Instead of casting the pointer before the load, cast
10597 // the result of the loaded value.
10598 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10599 CI->getName(),
10600 LI.isVolatile()),LI);
10601 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000010602 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000010603 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000010604 }
10605 }
10606 return 0;
10607}
10608
Chris Lattnerc10aced2004-09-19 18:43:46 +000010609/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +000010610/// from this value cannot trap. If it is not obviously safe to load from the
10611/// specified pointer, we do a quick local scan of the basic block containing
10612/// ScanFrom, to determine if the address is already accessed.
10613static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +000010614 // If it is an alloca it is always safe to load from.
10615 if (isa<AllocaInst>(V)) return true;
10616
Duncan Sands46318cd2007-09-19 10:25:38 +000010617 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +000010618 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +000010619 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +000010620 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +000010621
10622 // Otherwise, be a little bit agressive by scanning the local block where we
10623 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010624 // from/to. If so, the previous load or store would have already trapped,
10625 // so there is no harm doing an extra load (also, CSE will later eliminate
10626 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +000010627 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10628
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010629 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +000010630 --BBI;
10631
10632 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10633 if (LI->getOperand(0) == V) return true;
10634 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10635 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +000010636
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +000010637 }
Chris Lattner8a375202004-09-19 19:18:10 +000010638 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +000010639}
10640
Chris Lattner8d2e8882007-08-11 18:48:48 +000010641/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10642/// until we find the underlying object a pointer is referring to or something
10643/// we don't understand. Note that the returned pointer may be offset from the
10644/// input, because we ignore GEP indices.
10645static Value *GetUnderlyingObject(Value *Ptr) {
10646 while (1) {
10647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10648 if (CE->getOpcode() == Instruction::BitCast ||
10649 CE->getOpcode() == Instruction::GetElementPtr)
10650 Ptr = CE->getOperand(0);
10651 else
10652 return Ptr;
10653 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10654 Ptr = BCI->getOperand(0);
10655 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10656 Ptr = GEP->getOperand(0);
10657 } else {
10658 return Ptr;
10659 }
10660 }
10661}
10662
Chris Lattner833b8a42003-06-26 05:06:25 +000010663Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10664 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000010665
Dan Gohman9941f742007-07-20 16:34:21 +000010666 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010667 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10668 if (KnownAlign >
10669 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10670 LI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010671 LI.setAlignment(KnownAlign);
10672
Chris Lattner37366c12005-05-01 04:24:53 +000010673 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000010674 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000010675 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000010676 return Res;
10677
10678 // None of the following transforms are legal for volatile loads.
10679 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000010680
Chris Lattner62f254d2005-09-12 22:00:15 +000010681 if (&LI.getParent()->front() != &LI) {
10682 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010683 // If the instruction immediately before this is a store to the same
10684 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +000010685 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10686 if (SI->getOperand(1) == LI.getOperand(0))
10687 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +000010688 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10689 if (LIB->getOperand(0) == LI.getOperand(0))
10690 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +000010691 }
Chris Lattner37366c12005-05-01 04:24:53 +000010692
Christopher Lambb15147e2007-12-29 07:56:53 +000010693 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10694 const Value *GEPI0 = GEPI->getOperand(0);
10695 // TODO: Consider a target hook for valid address spaces for this xform.
10696 if (isa<ConstantPointerNull>(GEPI0) &&
10697 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000010698 // Insert a new store to null instruction before the load to indicate
10699 // that this code is not reachable. We do this instead of inserting
10700 // an unreachable instruction directly because we cannot modify the
10701 // CFG.
10702 new StoreInst(UndefValue::get(LI.getType()),
10703 Constant::getNullValue(Op->getType()), &LI);
10704 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10705 }
Christopher Lambb15147e2007-12-29 07:56:53 +000010706 }
Chris Lattner37366c12005-05-01 04:24:53 +000010707
Chris Lattnere87597f2004-10-16 18:11:37 +000010708 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000010709 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000010710 // TODO: Consider a target hook for valid address spaces for this xform.
10711 if (isa<UndefValue>(C) || (C->isNullValue() &&
10712 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000010713 // Insert a new store to null instruction before the load to indicate that
10714 // this code is not reachable. We do this instead of inserting an
10715 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +000010716 new StoreInst(UndefValue::get(LI.getType()),
10717 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +000010718 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010719 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010720
Chris Lattnere87597f2004-10-16 18:11:37 +000010721 // Instcombine load (constant global) into the value loaded.
10722 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010723 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +000010724 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000010725
Chris Lattnere87597f2004-10-16 18:11:37 +000010726 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010727 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000010728 if (CE->getOpcode() == Instruction::GetElementPtr) {
10729 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +000010730 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +000010731 if (Constant *V =
10732 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +000010733 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000010734 if (CE->getOperand(0)->isNullValue()) {
10735 // Insert a new store to null instruction before the load to indicate
10736 // that this code is not reachable. We do this instead of inserting
10737 // an unreachable instruction directly because we cannot modify the
10738 // CFG.
10739 new StoreInst(UndefValue::get(LI.getType()),
10740 Constant::getNullValue(Op->getType()), &LI);
10741 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10742 }
10743
Reid Spencer3da59db2006-11-27 01:05:10 +000010744 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000010745 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000010746 return Res;
10747 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010748 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010749 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000010750
10751 // If this load comes from anywhere in a constant global, and if the global
10752 // is all undef or zero, we know what it loads.
10753 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10754 if (GV->isConstant() && GV->hasInitializer()) {
10755 if (GV->getInitializer()->isNullValue())
10756 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10757 else if (isa<UndefValue>(GV->getInitializer()))
10758 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10759 }
10760 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000010761
Chris Lattner37366c12005-05-01 04:24:53 +000010762 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010763 // Change select and PHI nodes to select values instead of addresses: this
10764 // helps alias analysis out a lot, allows many others simplifications, and
10765 // exposes redundancy in the code.
10766 //
10767 // Note that we cannot do the transformation unless we know that the
10768 // introduced loads cannot trap! Something like this is valid as long as
10769 // the condition is always false: load (select bool %C, int* null, int* %G),
10770 // but it would not be valid if we transformed it to load from null
10771 // unconditionally.
10772 //
10773 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10774 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000010775 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10776 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000010777 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010778 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010779 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000010780 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000010781 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000010782 }
10783
Chris Lattner684fe212004-09-23 15:46:00 +000010784 // load (select (cond, null, P)) -> load P
10785 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10786 if (C->isNullValue()) {
10787 LI.setOperand(0, SI->getOperand(2));
10788 return &LI;
10789 }
10790
10791 // load (select (cond, P, null)) -> load P
10792 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10793 if (C->isNullValue()) {
10794 LI.setOperand(0, SI->getOperand(1));
10795 return &LI;
10796 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000010797 }
10798 }
Chris Lattner833b8a42003-06-26 05:06:25 +000010799 return 0;
10800}
10801
Reid Spencer55af2b52007-01-19 21:20:31 +000010802/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010803/// when possible.
10804static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10805 User *CI = cast<User>(SI.getOperand(1));
10806 Value *CastOp = CI->getOperand(0);
10807
10808 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10809 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10810 const Type *SrcPTy = SrcTy->getElementType();
10811
Reid Spencer42230162007-01-22 05:51:25 +000010812 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010813 // If the source is an array, the code below will not succeed. Check to
10814 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10815 // constants.
10816 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10817 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10818 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000010819 Value* Idxs[2];
10820 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10821 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010822 SrcTy = cast<PointerType>(CastOp->getType());
10823 SrcPTy = SrcTy->getElementType();
10824 }
10825
Reid Spencer67f827c2007-01-20 23:35:48 +000010826 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10827 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10828 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010829
10830 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +000010831 // the same size. Instead of casting the pointer before
10832 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010833 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +000010834 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +000010835 Instruction::CastOps opcode = Instruction::BitCast;
10836 const Type* CastSrcTy = SIOp0->getType();
10837 const Type* CastDstTy = SrcPTy;
10838 if (isa<PointerType>(CastDstTy)) {
10839 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +000010840 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +000010841 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +000010842 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +000010843 opcode = Instruction::PtrToInt;
10844 }
10845 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +000010846 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010847 else
Reid Spencer3da59db2006-11-27 01:05:10 +000010848 NewCast = IC.InsertNewInstBefore(
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010849 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Reid Spencer75153962007-01-18 18:54:33 +000010850 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010851 return new StoreInst(NewCast, CastOp);
10852 }
10853 }
10854 }
10855 return 0;
10856}
10857
Chris Lattner2f503e62005-01-31 05:36:43 +000010858Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10859 Value *Val = SI.getOperand(0);
10860 Value *Ptr = SI.getOperand(1);
10861
10862 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000010863 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010864 ++NumCombined;
10865 return 0;
10866 }
Chris Lattner836692d2007-01-15 06:51:56 +000010867
10868 // If the RHS is an alloca with a single use, zapify the store, making the
10869 // alloca dead.
Chris Lattnercea1fdd2008-04-29 04:58:38 +000010870 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Chris Lattner836692d2007-01-15 06:51:56 +000010871 if (isa<AllocaInst>(Ptr)) {
10872 EraseInstFromFunction(SI);
10873 ++NumCombined;
10874 return 0;
10875 }
10876
10877 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10878 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10879 GEP->getOperand(0)->hasOneUse()) {
10880 EraseInstFromFunction(SI);
10881 ++NumCombined;
10882 return 0;
10883 }
10884 }
Chris Lattner2f503e62005-01-31 05:36:43 +000010885
Dan Gohman9941f742007-07-20 16:34:21 +000010886 // Attempt to improve the alignment.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010887 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10888 if (KnownAlign >
10889 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10890 SI.getAlignment()))
Dan Gohman9941f742007-07-20 16:34:21 +000010891 SI.setAlignment(KnownAlign);
10892
Chris Lattner9ca96412006-02-08 03:25:32 +000010893 // Do really simple DSE, to catch cases where there are several consequtive
10894 // stores to the same location, separated by a few arithmetic operations. This
10895 // situation often occurs with bitfield accesses.
10896 BasicBlock::iterator BBI = &SI;
10897 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10898 --ScanInsts) {
10899 --BBI;
10900
10901 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10902 // Prev store isn't volatile, and stores to the same location?
10903 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10904 ++NumDeadStore;
10905 ++BBI;
10906 EraseInstFromFunction(*PrevSI);
10907 continue;
10908 }
10909 break;
10910 }
10911
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010912 // If this is a load, we have to stop. However, if the loaded value is from
10913 // the pointer we're loading and is producing the pointer we're storing,
10914 // then *this* store is dead (X = load P; store X -> P).
10915 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010916 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010917 EraseInstFromFunction(SI);
10918 ++NumCombined;
10919 return 0;
10920 }
10921 // Otherwise, this is a load from some other location. Stores before it
10922 // may not be dead.
10923 break;
10924 }
10925
Chris Lattner9ca96412006-02-08 03:25:32 +000010926 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000010927 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010928 break;
10929 }
10930
10931
10932 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010933
10934 // store X, null -> turns into 'unreachable' in SimplifyCFG
10935 if (isa<ConstantPointerNull>(Ptr)) {
10936 if (!isa<UndefValue>(Val)) {
10937 SI.setOperand(0, UndefValue::get(Val->getType()));
10938 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010939 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010940 ++NumCombined;
10941 }
10942 return 0; // Do not modify these!
10943 }
10944
10945 // store undef, Ptr -> noop
10946 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010947 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010948 ++NumCombined;
10949 return 0;
10950 }
10951
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010952 // If the pointer destination is a cast, see if we can fold the cast into the
10953 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010954 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010955 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10956 return Res;
10957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010958 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010959 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10960 return Res;
10961
Chris Lattner408902b2005-09-12 23:23:25 +000010962
10963 // If this store is the last instruction in the basic block, and if the block
10964 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010965 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010966 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010967 if (BI->isUnconditional())
10968 if (SimplifyStoreAtEndOfBlock(SI))
10969 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010970
Chris Lattner2f503e62005-01-31 05:36:43 +000010971 return 0;
10972}
10973
Chris Lattner3284d1f2007-04-15 00:07:55 +000010974/// SimplifyStoreAtEndOfBlock - Turn things like:
10975/// if () { *P = v1; } else { *P = v2 }
10976/// into a phi node with a store in the successor.
10977///
Chris Lattner31755a02007-04-15 01:02:18 +000010978/// Simplify things like:
10979/// *P = v1; if () { *P = v2; }
10980/// into a phi node with a store in the successor.
10981///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010982bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10983 BasicBlock *StoreBB = SI.getParent();
10984
10985 // Check to see if the successor block has exactly two incoming edges. If
10986 // so, see if the other predecessor contains a store to the same location.
10987 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010988 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010989
10990 // Determine whether Dest has exactly two predecessors and, if so, compute
10991 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010992 pred_iterator PI = pred_begin(DestBB);
10993 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010994 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010995 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010996 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010997 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010998 return false;
10999
11000 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011001 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011002 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011003 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011004 }
Chris Lattner31755a02007-04-15 01:02:18 +000011005 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011006 return false;
11007
11008
Chris Lattner31755a02007-04-15 01:02:18 +000011009 // Verify that the other block ends in a branch and is not otherwise empty.
11010 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011011 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011012 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011013 return false;
11014
Chris Lattner31755a02007-04-15 01:02:18 +000011015 // If the other block ends in an unconditional branch, check for the 'if then
11016 // else' case. there is an instruction before the branch.
11017 StoreInst *OtherStore = 0;
11018 if (OtherBr->isUnconditional()) {
11019 // If this isn't a store, or isn't a store to the same location, bail out.
11020 --BBI;
11021 OtherStore = dyn_cast<StoreInst>(BBI);
11022 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11023 return false;
11024 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011025 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011026 // destinations is StoreBB, then we have the if/then case.
11027 if (OtherBr->getSuccessor(0) != StoreBB &&
11028 OtherBr->getSuccessor(1) != StoreBB)
11029 return false;
11030
11031 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011032 // if/then triangle. See if there is a store to the same ptr as SI that
11033 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011034 for (;; --BBI) {
11035 // Check to see if we find the matching store.
11036 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11037 if (OtherStore->getOperand(1) != SI.getOperand(1))
11038 return false;
11039 break;
11040 }
Chris Lattnerd717c182007-05-05 22:32:24 +000011041 // If we find something that may be using the stored value, or if we run
11042 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000011043 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11044 BBI == OtherBB->begin())
11045 return false;
11046 }
11047
11048 // In order to eliminate the store in OtherBr, we have to
11049 // make sure nothing reads the stored value in StoreBB.
11050 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11051 // FIXME: This should really be AA driven.
11052 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11053 return false;
11054 }
11055 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011056
Chris Lattner31755a02007-04-15 01:02:18 +000011057 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011058 Value *MergedVal = OtherStore->getOperand(0);
11059 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011060 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011061 PN->reserveOperandSpace(2);
11062 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011063 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11064 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011065 }
11066
11067 // Advance to a place where it is safe to insert the new store and
11068 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000011069 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011070 while (isa<PHINode>(BBI)) ++BBI;
11071 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11072 OtherStore->isVolatile()), *BBI);
11073
11074 // Nuke the old stores.
11075 EraseInstFromFunction(SI);
11076 EraseInstFromFunction(*OtherStore);
11077 ++NumCombined;
11078 return true;
11079}
11080
Chris Lattner2f503e62005-01-31 05:36:43 +000011081
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011082Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11083 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011084 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011085 BasicBlock *TrueDest;
11086 BasicBlock *FalseDest;
11087 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11088 !isa<Constant>(X)) {
11089 // Swap Destinations and condition...
11090 BI.setCondition(X);
11091 BI.setSuccessor(0, FalseDest);
11092 BI.setSuccessor(1, TrueDest);
11093 return &BI;
11094 }
11095
Reid Spencere4d87aa2006-12-23 06:05:41 +000011096 // Cannonicalize fcmp_one -> fcmp_oeq
11097 FCmpInst::Predicate FPred; Value *Y;
11098 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11099 TrueDest, FalseDest)))
11100 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11101 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11102 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011103 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011104 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11105 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011106 // Swap Destinations and condition...
11107 BI.setCondition(NewSCC);
11108 BI.setSuccessor(0, FalseDest);
11109 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011110 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011111 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011112 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011113 return &BI;
11114 }
11115
11116 // Cannonicalize icmp_ne -> icmp_eq
11117 ICmpInst::Predicate IPred;
11118 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11119 TrueDest, FalseDest)))
11120 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11121 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11122 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11123 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000011124 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000011125 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11126 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000011127 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011128 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011129 BI.setSuccessor(0, FalseDest);
11130 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000011131 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000011132 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011133 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000011134 return &BI;
11135 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011136
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011137 return 0;
11138}
Chris Lattner0864acf2002-11-04 16:18:53 +000011139
Chris Lattner46238a62004-07-03 00:26:11 +000011140Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11141 Value *Cond = SI.getCondition();
11142 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11143 if (I->getOpcode() == Instruction::Add)
11144 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11145 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11146 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000011147 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011148 AddRHS));
11149 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000011150 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011151 return &SI;
11152 }
11153 }
11154 return 0;
11155}
11156
Chris Lattner220b0cf2006-03-05 00:22:33 +000011157/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11158/// is to leave as a vector operation.
11159static bool CheapToScalarize(Value *V, bool isConstant) {
11160 if (isa<ConstantAggregateZero>(V))
11161 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011162 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011163 if (isConstant) return true;
11164 // If all elts are the same, we can extract.
11165 Constant *Op0 = C->getOperand(0);
11166 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11167 if (C->getOperand(i) != Op0)
11168 return false;
11169 return true;
11170 }
11171 Instruction *I = dyn_cast<Instruction>(V);
11172 if (!I) return false;
11173
11174 // Insert element gets simplified to the inserted element or is deleted if
11175 // this is constant idx extract element and its a constant idx insertelt.
11176 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11177 isa<ConstantInt>(I->getOperand(2)))
11178 return true;
11179 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11180 return true;
11181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11182 if (BO->hasOneUse() &&
11183 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11184 CheapToScalarize(BO->getOperand(1), isConstant)))
11185 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011186 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11187 if (CI->hasOneUse() &&
11188 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11189 CheapToScalarize(CI->getOperand(1), isConstant)))
11190 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011191
11192 return false;
11193}
11194
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011195/// Read and decode a shufflevector mask.
11196///
11197/// It turns undef elements into values that are larger than the number of
11198/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000011199static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11200 unsigned NElts = SVI->getType()->getNumElements();
11201 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11202 return std::vector<unsigned>(NElts, 0);
11203 if (isa<UndefValue>(SVI->getOperand(2)))
11204 return std::vector<unsigned>(NElts, 2*NElts);
11205
11206 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011207 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000011208 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11209 if (isa<UndefValue>(CP->getOperand(i)))
11210 Result.push_back(NElts*2); // undef -> 8
11211 else
Reid Spencerb83eb642006-10-20 07:07:24 +000011212 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000011213 return Result;
11214}
11215
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011216/// FindScalarElement - Given a vector and an element number, see if the scalar
11217/// value is already around as a register, for example if it were inserted then
11218/// extracted from the vector.
11219static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011220 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11221 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000011222 unsigned Width = PTy->getNumElements();
11223 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011224 return UndefValue::get(PTy->getElementType());
11225
11226 if (isa<UndefValue>(V))
11227 return UndefValue::get(PTy->getElementType());
11228 else if (isa<ConstantAggregateZero>(V))
11229 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000011230 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011231 return CP->getOperand(EltNo);
11232 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11233 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000011234 if (!isa<ConstantInt>(III->getOperand(2)))
11235 return 0;
11236 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011237
11238 // If this is an insert to the element we are looking for, return the
11239 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000011240 if (EltNo == IIElt)
11241 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011242
11243 // Otherwise, the insertelement doesn't modify the value, recurse on its
11244 // vector input.
11245 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000011246 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000011247 unsigned InEl = getShuffleMask(SVI)[EltNo];
11248 if (InEl < Width)
11249 return FindScalarElement(SVI->getOperand(0), InEl);
11250 else if (InEl < Width*2)
11251 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11252 else
11253 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011254 }
11255
11256 // Otherwise, we don't know.
11257 return 0;
11258}
11259
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011260Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011261
Dan Gohman07a96762007-07-16 14:29:03 +000011262 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000011263 if (isa<UndefValue>(EI.getOperand(0)))
11264 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11265
Dan Gohman07a96762007-07-16 14:29:03 +000011266 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000011267 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11268 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11269
Reid Spencer9d6565a2007-02-15 02:26:10 +000011270 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000011271 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011272 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000011273 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011274 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000011275 if (C->getOperand(i) != op0) {
11276 op0 = 0;
11277 break;
11278 }
11279 if (op0)
11280 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011281 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000011282
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011283 // If extracting a specified index from the vector, see if we can recursively
11284 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000011285 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000011286 unsigned IndexVal = IdxC->getZExtValue();
11287 unsigned VectorWidth =
11288 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11289
11290 // If this is extracting an invalid index, turn this into undef, to avoid
11291 // crashing the code below.
11292 if (IndexVal >= VectorWidth)
11293 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11294
Chris Lattner867b99f2006-10-05 06:55:50 +000011295 // This instruction only demands the single element from the input vector.
11296 // If the input vector has a single use, simplify it based on this use
11297 // property.
Chris Lattner85464092007-04-09 01:37:55 +000011298 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000011299 uint64_t UndefElts;
11300 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000011301 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000011302 UndefElts)) {
11303 EI.setOperand(0, V);
11304 return &EI;
11305 }
11306 }
11307
Reid Spencerb83eb642006-10-20 07:07:24 +000011308 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011309 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000011310
11311 // If the this extractelement is directly using a bitcast from a vector of
11312 // the same number of elements, see if we can find the source element from
11313 // it. In this case, we will end up needing to bitcast the scalars.
11314 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11315 if (const VectorType *VT =
11316 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11317 if (VT->getNumElements() == VectorWidth)
11318 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11319 return new BitCastInst(Elt, EI.getType());
11320 }
Chris Lattner389a6f52006-04-10 23:06:36 +000011321 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000011322
Chris Lattner73fa49d2006-05-25 22:53:38 +000011323 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011324 if (I->hasOneUse()) {
11325 // Push extractelement into predecessor operation if legal and
11326 // profitable to do so
11327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011328 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11329 if (CheapToScalarize(BO, isConstantElt)) {
11330 ExtractElementInst *newEI0 =
11331 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11332 EI.getName()+".lhs");
11333 ExtractElementInst *newEI1 =
11334 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11335 EI.getName()+".rhs");
11336 InsertNewInstBefore(newEI0, EI);
11337 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011338 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000011339 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000011340 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000011341 unsigned AS =
11342 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000011343 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11344 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011345 GetElementPtrInst *GEP =
11346 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011347 InsertNewInstBefore(GEP, EI);
11348 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000011349 }
11350 }
11351 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11352 // Extracting the inserted element?
11353 if (IE->getOperand(2) == EI.getOperand(1))
11354 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11355 // If the inserted and extracted elements are constants, they must not
11356 // be the same value, extract from the pre-inserted value instead.
11357 if (isa<Constant>(IE->getOperand(2)) &&
11358 isa<Constant>(EI.getOperand(1))) {
11359 AddUsesToWorkList(EI);
11360 EI.setOperand(0, IE->getOperand(0));
11361 return &EI;
11362 }
11363 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11364 // If this is extracting an element from a shufflevector, figure out where
11365 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000011366 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11367 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000011368 Value *Src;
11369 if (SrcIdx < SVI->getType()->getNumElements())
11370 Src = SVI->getOperand(0);
11371 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11372 SrcIdx -= SVI->getType()->getNumElements();
11373 Src = SVI->getOperand(1);
11374 } else {
11375 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000011376 }
Chris Lattner867b99f2006-10-05 06:55:50 +000011377 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011378 }
11379 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000011380 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011381 return 0;
11382}
11383
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011384/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11385/// elements from either LHS or RHS, return the shuffle mask and true.
11386/// Otherwise, return false.
11387static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11388 std::vector<Constant*> &Mask) {
11389 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11390 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011391 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011392
11393 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011394 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011395 return true;
11396 } else if (V == LHS) {
11397 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011398 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011399 return true;
11400 } else if (V == RHS) {
11401 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011402 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011403 return true;
11404 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11405 // If this is an insert of an extract from some other vector, include it.
11406 Value *VecOp = IEI->getOperand(0);
11407 Value *ScalarOp = IEI->getOperand(1);
11408 Value *IdxOp = IEI->getOperand(2);
11409
Chris Lattnerd929f062006-04-27 21:14:21 +000011410 if (!isa<ConstantInt>(IdxOp))
11411 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000011412 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000011413
11414 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11415 // Okay, we can handle this if the vector we are insertinting into is
11416 // transitively ok.
11417 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11418 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011419 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000011420 return true;
11421 }
11422 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11423 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011424 EI->getOperand(0)->getType() == V->getType()) {
11425 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011426 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011427
11428 // This must be extracting from either LHS or RHS.
11429 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11430 // Okay, we can handle this if the vector we are insertinting into is
11431 // transitively ok.
11432 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11433 // If so, update the mask to reflect the inserted value.
11434 if (EI->getOperand(0) == LHS) {
11435 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011436 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011437 } else {
11438 assert(EI->getOperand(0) == RHS);
11439 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011440 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011441
11442 }
11443 return true;
11444 }
11445 }
11446 }
11447 }
11448 }
11449 // TODO: Handle shufflevector here!
11450
11451 return false;
11452}
11453
11454/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11455/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11456/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000011457static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011458 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000011459 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011460 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000011461 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000011462 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000011463
11464 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011465 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011466 return V;
11467 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011468 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000011469 return V;
11470 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11471 // If this is an insert of an extract from some other vector, include it.
11472 Value *VecOp = IEI->getOperand(0);
11473 Value *ScalarOp = IEI->getOperand(1);
11474 Value *IdxOp = IEI->getOperand(2);
11475
11476 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11477 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11478 EI->getOperand(0)->getType() == V->getType()) {
11479 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000011480 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11481 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011482
11483 // Either the extracted from or inserted into vector must be RHSVec,
11484 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011485 if (EI->getOperand(0) == RHS || RHS == 0) {
11486 RHS = EI->getOperand(0);
11487 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011488 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000011489 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011490 return V;
11491 }
11492
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011493 if (VecOp == RHS) {
11494 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000011495 // Everything but the extracted element is replaced with the RHS.
11496 for (unsigned i = 0; i != NumElts; ++i) {
11497 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011498 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000011499 }
11500 return V;
11501 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011502
11503 // If this insertelement is a chain that comes from exactly these two
11504 // vectors, return the vector and the effective shuffle.
11505 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11506 return EI->getOperand(0);
11507
Chris Lattnerefb47352006-04-15 01:39:45 +000011508 }
11509 }
11510 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011511 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000011512
11513 // Otherwise, can't do anything fancy. Return an identity vector.
11514 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011515 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000011516 return V;
11517}
11518
11519Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11520 Value *VecOp = IE.getOperand(0);
11521 Value *ScalarOp = IE.getOperand(1);
11522 Value *IdxOp = IE.getOperand(2);
11523
Chris Lattner599ded12007-04-09 01:11:16 +000011524 // Inserting an undef or into an undefined place, remove this.
11525 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11526 ReplaceInstUsesWith(IE, VecOp);
11527
Chris Lattnerefb47352006-04-15 01:39:45 +000011528 // If the inserted element was extracted from some other vector, and if the
11529 // indexes are constant, try to turn this into a shufflevector operation.
11530 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11531 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11532 EI->getOperand(0)->getType() == IE.getType()) {
11533 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000011534 unsigned ExtractedIdx =
11535 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000011536 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000011537
11538 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11539 return ReplaceInstUsesWith(IE, VecOp);
11540
11541 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11542 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11543
11544 // If we are extracting a value from a vector, then inserting it right
11545 // back into the same place, just use the input vector.
11546 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11547 return ReplaceInstUsesWith(IE, VecOp);
11548
11549 // We could theoretically do this for ANY input. However, doing so could
11550 // turn chains of insertelement instructions into a chain of shufflevector
11551 // instructions, and right now we do not merge shufflevectors. As such,
11552 // only do this in a situation where it is clear that there is benefit.
11553 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11554 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11555 // the values of VecOp, except then one read from EIOp0.
11556 // Build a new shuffle mask.
11557 std::vector<Constant*> Mask;
11558 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000011559 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000011560 else {
11561 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000011562 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000011563 NumVectorElts));
11564 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000011565 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000011566 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000011567 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011568 }
11569
11570 // If this insertelement isn't used by some other insertelement, turn it
11571 // (and any insertelements it points to), into one big shuffle.
11572 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11573 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000011574 Value *RHS = 0;
11575 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11576 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11577 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000011578 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000011579 }
11580 }
11581 }
11582
11583 return 0;
11584}
11585
11586
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011587Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11588 Value *LHS = SVI.getOperand(0);
11589 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000011590 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011591
11592 bool MadeChange = false;
11593
Chris Lattner867b99f2006-10-05 06:55:50 +000011594 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000011595 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011596 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11597
Chris Lattnere4929dd2007-01-05 07:36:08 +000011598 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000011599 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000011600 if (isa<UndefValue>(SVI.getOperand(1))) {
11601 // Scan to see if there are any references to the RHS. If so, replace them
11602 // with undef element refs and set MadeChange to true.
11603 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11604 if (Mask[i] >= e && Mask[i] != 2*e) {
11605 Mask[i] = 2*e;
11606 MadeChange = true;
11607 }
11608 }
11609
11610 if (MadeChange) {
11611 // Remap any references to RHS to use LHS.
11612 std::vector<Constant*> Elts;
11613 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11614 if (Mask[i] == 2*e)
11615 Elts.push_back(UndefValue::get(Type::Int32Ty));
11616 else
11617 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11618 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000011619 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000011620 }
11621 }
Chris Lattnerefb47352006-04-15 01:39:45 +000011622
Chris Lattner863bcff2006-05-25 23:48:38 +000011623 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11624 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11625 if (LHS == RHS || isa<UndefValue>(LHS)) {
11626 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011627 // shuffle(undef,undef,mask) -> undef.
11628 return ReplaceInstUsesWith(SVI, LHS);
11629 }
11630
Chris Lattner863bcff2006-05-25 23:48:38 +000011631 // Remap any references to RHS to use LHS.
11632 std::vector<Constant*> Elts;
11633 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000011634 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000011635 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011636 else {
11637 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11638 (Mask[i] < e && isa<UndefValue>(LHS)))
11639 Mask[i] = 2*e; // Turn into undef.
11640 else
11641 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000011642 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011643 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011644 }
Chris Lattner863bcff2006-05-25 23:48:38 +000011645 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011646 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000011647 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011648 LHS = SVI.getOperand(0);
11649 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011650 MadeChange = true;
11651 }
11652
Chris Lattner7b2e27922006-05-26 00:29:06 +000011653 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000011654 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000011655
Chris Lattner863bcff2006-05-25 23:48:38 +000011656 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11657 if (Mask[i] >= e*2) continue; // Ignore undef values.
11658 // Is this an identity shuffle of the LHS value?
11659 isLHSID &= (Mask[i] == i);
11660
11661 // Is this an identity shuffle of the RHS value?
11662 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000011663 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011664
Chris Lattner863bcff2006-05-25 23:48:38 +000011665 // Eliminate identity shuffles.
11666 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11667 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011668
Chris Lattner7b2e27922006-05-26 00:29:06 +000011669 // If the LHS is a shufflevector itself, see if we can combine it with this
11670 // one without producing an unusual shuffle. Here we are really conservative:
11671 // we are absolutely afraid of producing a shuffle mask not in the input
11672 // program, because the code gen may not be smart enough to turn a merged
11673 // shuffle into two specific shuffles: it may produce worse code. As such,
11674 // we only merge two shuffles if the result is one of the two input shuffle
11675 // masks. In this case, merging the shuffles just removes one instruction,
11676 // which we know is safe. This is good for things like turning:
11677 // (splat(splat)) -> splat.
11678 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11679 if (isa<UndefValue>(RHS)) {
11680 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11681
11682 std::vector<unsigned> NewMask;
11683 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11684 if (Mask[i] >= 2*e)
11685 NewMask.push_back(2*e);
11686 else
11687 NewMask.push_back(LHSMask[Mask[i]]);
11688
11689 // If the result mask is equal to the src shuffle or this shuffle mask, do
11690 // the replacement.
11691 if (NewMask == LHSMask || NewMask == Mask) {
11692 std::vector<Constant*> Elts;
11693 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11694 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011695 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011696 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011697 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011698 }
11699 }
11700 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11701 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000011702 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000011703 }
11704 }
11705 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000011706
Chris Lattnera844fc4c2006-04-10 22:45:52 +000011707 return MadeChange ? &SVI : 0;
11708}
11709
11710
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011711
Chris Lattnerea1c4542004-12-08 23:43:58 +000011712
11713/// TryToSinkInstruction - Try to move the specified instruction from its
11714/// current block into the beginning of DestBlock, which can only happen if it's
11715/// safe to move the instruction past all of the instructions between it and the
11716/// end of its block.
11717static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11718 assert(I->hasOneUse() && "Invariants didn't hold!");
11719
Chris Lattner108e9022005-10-27 17:13:11 +000011720 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnerbfc538c2008-05-09 15:07:33 +000011721 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11722 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000011723
Chris Lattnerea1c4542004-12-08 23:43:58 +000011724 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000011725 if (isa<AllocaInst>(I) && I->getParent() ==
11726 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000011727 return false;
11728
Chris Lattner96a52a62004-12-09 07:14:34 +000011729 // We can only sink load instructions if there is nothing between the load and
11730 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000011731 if (I->mayReadFromMemory()) {
11732 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000011733 Scan != E; ++Scan)
11734 if (Scan->mayWriteToMemory())
11735 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000011736 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000011737
11738 BasicBlock::iterator InsertPos = DestBlock->begin();
11739 while (isa<PHINode>(InsertPos)) ++InsertPos;
11740
Chris Lattner4bc5f802005-08-08 19:11:57 +000011741 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000011742 ++NumSunkInst;
11743 return true;
11744}
11745
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011746
11747/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11748/// all reachable code to the worklist.
11749///
11750/// This has a couple of tricks to make the code faster and more powerful. In
11751/// particular, we constant fold and DCE instructions as we go, to avoid adding
11752/// them to the worklist (this significantly speeds up instcombine on code where
11753/// many instructions are dead or constant). Additionally, if we find a branch
11754/// whose condition is a known constant, we only visit the reachable successors.
11755///
11756static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000011757 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000011758 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011759 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000011760 std::vector<BasicBlock*> Worklist;
11761 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011762
Chris Lattner2c7718a2007-03-23 19:17:18 +000011763 while (!Worklist.empty()) {
11764 BB = Worklist.back();
11765 Worklist.pop_back();
11766
11767 // We have now visited this block! If we've already been here, ignore it.
11768 if (!Visited.insert(BB)) continue;
11769
11770 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11771 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011772
Chris Lattner2c7718a2007-03-23 19:17:18 +000011773 // DCE instruction if trivially dead.
11774 if (isInstructionTriviallyDead(Inst)) {
11775 ++NumDeadInst;
11776 DOUT << "IC: DCE: " << *Inst;
11777 Inst->eraseFromParent();
11778 continue;
11779 }
11780
11781 // ConstantProp instruction if trivially constant.
11782 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11783 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11784 Inst->replaceAllUsesWith(C);
11785 ++NumConstProp;
11786 Inst->eraseFromParent();
11787 continue;
11788 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000011789
Chris Lattner2c7718a2007-03-23 19:17:18 +000011790 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011791 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000011792
11793 // Recursively visit successors. If this is a branch or switch on a
11794 // constant, only visit the reachable successor.
11795 TerminatorInst *TI = BB->getTerminator();
11796 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11797 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11798 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000011799 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011800 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011801 continue;
11802 }
11803 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11804 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11805 // See if this is an explicit destination.
11806 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11807 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000011808 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000011809 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000011810 continue;
11811 }
11812
11813 // Otherwise it is the default destination.
11814 Worklist.push_back(SI->getSuccessor(0));
11815 continue;
11816 }
11817 }
11818
11819 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11820 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011821 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011822}
11823
Chris Lattnerec9c3582007-03-03 02:04:50 +000011824bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011825 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000011826 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000011827
11828 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11829 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000011830
Chris Lattnerb3d59702005-07-07 20:40:38 +000011831 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011832 // Do a depth-first traversal of the function, populate the worklist with
11833 // the reachable instructions. Ignore blocks that are not reachable. Keep
11834 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000011835 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000011836 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000011837
Chris Lattnerb3d59702005-07-07 20:40:38 +000011838 // Do a quick scan over the function. If we find any blocks that are
11839 // unreachable, remove any instructions inside of them. This prevents
11840 // the instcombine code from having to deal with some bad special cases.
11841 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11842 if (!Visited.count(BB)) {
11843 Instruction *Term = BB->getTerminator();
11844 while (Term != BB->begin()) { // Remove instrs bottom-up
11845 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000011846
Bill Wendlingb7427032006-11-26 09:46:52 +000011847 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000011848 ++NumDeadInst;
11849
11850 if (!I->use_empty())
11851 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11852 I->eraseFromParent();
11853 }
11854 }
11855 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011856
Chris Lattnerdbab3862007-03-02 21:28:56 +000011857 while (!Worklist.empty()) {
11858 Instruction *I = RemoveOneFromWorkList();
11859 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000011860
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011861 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000011862 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011863 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000011864 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011865 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000011866 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000011867
Bill Wendlingb7427032006-11-26 09:46:52 +000011868 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011869
11870 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011871 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011872 continue;
11873 }
Chris Lattner62b14df2002-09-02 04:59:56 +000011874
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011875 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000011876 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011877 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000011878
Chris Lattner8c8c66a2006-05-11 17:11:52 +000011879 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011880 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000011881 ReplaceInstUsesWith(*I, C);
11882
Chris Lattner62b14df2002-09-02 04:59:56 +000011883 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000011884 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000011885 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011886 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000011887 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000011888
Chris Lattnerea1c4542004-12-08 23:43:58 +000011889 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner2539e332008-05-08 17:37:37 +000011890 // FIXME: Remove GetResultInst test when first class support for aggregates
11891 // is implemented.
Devang Patelf944c9a2008-05-03 00:36:30 +000011892 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000011893 BasicBlock *BB = I->getParent();
11894 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11895 if (UserParent != BB) {
11896 bool UserIsSuccessor = false;
11897 // See if the user is one of our successors.
11898 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11899 if (*SI == UserParent) {
11900 UserIsSuccessor = true;
11901 break;
11902 }
11903
11904 // If the user is one of our immediate successors, and if that successor
11905 // only has us as a predecessors (we'd have to split the critical edge
11906 // otherwise), we can keep going.
11907 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11908 next(pred_begin(UserParent)) == pred_end(UserParent))
11909 // Okay, the CFG is simple enough, try to sink this instruction.
11910 Changed |= TryToSinkInstruction(I, UserParent);
11911 }
11912 }
11913
Chris Lattner8a2a3112001-12-14 16:52:21 +000011914 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011915#ifndef NDEBUG
11916 std::string OrigI;
11917#endif
11918 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011919 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011920 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011921 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011922 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011923 DOUT << "IC: Old = " << *I
11924 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011925
Chris Lattnerf523d062004-06-09 05:08:07 +000011926 // Everything uses the new instruction now.
11927 I->replaceAllUsesWith(Result);
11928
11929 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011930 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011931 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011932
Chris Lattner6934a042007-02-11 01:23:03 +000011933 // Move the name to the new instruction first.
11934 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011935
11936 // Insert the new instruction into the basic block...
11937 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011938 BasicBlock::iterator InsertPos = I;
11939
11940 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11941 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11942 ++InsertPos;
11943
11944 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011945
Chris Lattner00d51312004-05-01 23:27:23 +000011946 // Make sure that we reprocess all operands now that we reduced their
11947 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011948 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011949
Chris Lattnerf523d062004-06-09 05:08:07 +000011950 // Instructions can end up on the worklist more than once. Make sure
11951 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011952 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011953
11954 // Erase the old instruction.
11955 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011956 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011957#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011958 DOUT << "IC: Mod = " << OrigI
11959 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011960#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011961
Chris Lattner90ac28c2002-08-02 19:29:35 +000011962 // If the instruction was modified, it's possible that it is now dead.
11963 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011964 if (isInstructionTriviallyDead(I)) {
11965 // Make sure we process all operands now that we are reducing their
11966 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011967 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011968
Chris Lattner00d51312004-05-01 23:27:23 +000011969 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011970 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011971 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011972 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011973 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011974 AddToWorkList(I);
11975 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011976 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011977 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011978 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011979 }
11980 }
11981
Chris Lattnerec9c3582007-03-03 02:04:50 +000011982 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011983
11984 // Do an explicit clear, this shrinks the map if needed.
11985 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011986 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011987}
11988
Chris Lattnerec9c3582007-03-03 02:04:50 +000011989
11990bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011991 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11992
Chris Lattnerec9c3582007-03-03 02:04:50 +000011993 bool EverMadeChange = false;
11994
11995 // Iterate while there is work to do.
11996 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000011997 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000011998 EverMadeChange = true;
11999 return EverMadeChange;
12000}
12001
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012002FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012003 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012004}
Brian Gaeked0fde302003-11-11 22:41:34 +000012005